java.util.Calendar、java.util.Date、java.sql.timestamp

取得現在時間,"toString()"結果:

  • java.util.Calendar
        java.util.Calendar cal = java.util.Calendar.getInstance();
        System.out.println( cal );  // "java.util.GregorianCalendar[time=1525760873174,areFieldsSet=true,areAllFieldsSet=true,lenient=true,zone=sun.util.calendar.ZoneInfo[id="GMT+08:00",offset=28800000,dstSavings=0,useDaylight=false,transitions=0,lastRule=null],firstDayOfWeek=1,minimalDaysInFirstWeek=1,ERA=1,YEAR=2018,MONTH=4,WEEK_OF_YEAR=19,WEEK_OF_MONTH=2,DAY_OF_MONTH=8,DAY_OF_YEAR=128,DAY_OF_WEEK=3,DAY_OF_WEEK_IN_MONTH=2,AM_PM=1,HOUR=2,HOUR_OF_DAY=14,MINUTE=27,SECOND=53,MILLISECOND=174,ZONE_OFFSET=28800000,DST_OFFSET=0]"
    
  • java.util.Date
        java.util.Date utilDate = new java.util.Date();
        System.out.println( utilDate );  // "Tue May 08 14:24:13 GMT+08:00 2018"
    
  • java.sql.timestamp
        Timestamp timestamp = new Timestamp( System.currentTimeMillis() );
        System.out.println( sqlTstp );  // "2018-05-08 14:24:13.338"
    

參考:
How to get current timestamps in Java – Mkyong.com
 

 

轉換:(以下囉唆的印出,為提供參考轉前轉後的結果)

  • java.util.Calendar -> java.util.Date
        java.util.Calendar cal = java.util.Calendar.getInstance();
        java.util.Date utilDate = cal.getTime();
        System.out.println( cal );  // "java.util.GregorianCalendar[time=1525761440698,areFieldsSet=true,areAllFieldsSet=true,lenient=true,zone=sun.util.calendar.ZoneInfo[id="GMT+08:00",offset=28800000,dstSavings=0,useDaylight=false,transitions=0,lastRule=null],firstDayOfWeek=1,minimalDaysInFirstWeek=1,ERA=1,YEAR=2018,MONTH=4,WEEK_OF_YEAR=19,WEEK_OF_MONTH=2,DAY_OF_MONTH=8,DAY_OF_YEAR=128,DAY_OF_WEEK=3,DAY_OF_WEEK_IN_MONTH=2,AM_PM=1,HOUR=2,HOUR_OF_DAY=14,MINUTE=37,SECOND=20,MILLISECOND=698,ZONE_OFFSET=28800000,DST_OFFSET=0]"
        System.out.println( utilDate );  // "Tue May 08 14:37:20 GMT+08:00 2018"
    
  • java.util.Calendar -> java.sql.timestamp
        java.util.Calendar cal = java.util.Calendar.getInstance();
        java.sql.Timestamp sqlTstp = new java.sql.Timestamp( cal.getTimeInMillis() );
        System.out.println( cal );  // "java.util.GregorianCalendar[time=1525761204005,areFieldsSet=true,areAllFieldsSet=true,lenient=true,zone=sun.util.calendar.ZoneInfo[id="GMT+08:00",offset=28800000,dstSavings=0,useDaylight=false,transitions=0,lastRule=null],firstDayOfWeek=1,minimalDaysInFirstWeek=1,ERA=1,YEAR=2018,MONTH=4,WEEK_OF_YEAR=19,WEEK_OF_MONTH=2,DAY_OF_MONTH=8,DAY_OF_YEAR=128,DAY_OF_WEEK=3,DAY_OF_WEEK_IN_MONTH=2,AM_PM=1,HOUR=2,HOUR_OF_DAY=14,MINUTE=33,SECOND=24,MILLISECOND=5,ZONE_OFFSET=28800000,DST_OFFSET=0]"
        System.out.println( sqlTstp );  // "2018-05-08 14:33:24.005"
    

 

  • java.util.Date -> java.util.Calendar
        java.util.Date utilDate = new java.util.Date();
        java.util.Calendar cal = java.util.Calendar.getInstance();
        cal.setTime( utilDate );
        System.out.println( utilDate );  // "Tue May 08 14:27:53 GMT+08:00 2018"
        System.out.println( cal );  // "java.util.GregorianCalendar[time=1525760873174,areFieldsSet=true,areAllFieldsSet=true,lenient=true,zone=sun.util.calendar.ZoneInfo[id="GMT+08:00",offset=28800000,dstSavings=0,useDaylight=false,transitions=0,lastRule=null],firstDayOfWeek=1,minimalDaysInFirstWeek=1,ERA=1,YEAR=2018,MONTH=4,WEEK_OF_YEAR=19,WEEK_OF_MONTH=2,DAY_OF_MONTH=8,DAY_OF_YEAR=128,DAY_OF_WEEK=3,DAY_OF_WEEK_IN_MONTH=2,AM_PM=1,HOUR=2,HOUR_OF_DAY=14,MINUTE=27,SECOND=53,MILLISECOND=174,ZONE_OFFSET=28800000,DST_OFFSET=0]"
    
  • java.util.Date -> java.sql.timestamp
        java.util.Date utilDate = new java.util.Date();
        java.sql.Timestamp sqlTstp = new java.sql.Timestamp( utilDate.getTime() );  // long
        System.out.println( utilDate );  // "Tue May 08 14:24:13 GMT+08:00 2018"
        System.out.println( sqlTstp );  // "2018-05-08 14:24:13.338"
    

 

 

To ISO 8601 string format:

Example:
    2017-02-16T20:22:28+00:00
    2017-02-16T20:22:28.000+00:00

  • java.util.Calendar
        // Convert to java.util.Date first
  • java.util.Date
        java.util.Date date = new java.util.Date( System.currentTimeMillis() );
        java.text.SimpleDateFormat sdf = new java.text.SimpleDateFormat( "yyyy-MM-dd'T'HH:mm:ss.SSSXXX" );
        sdf.setTimeZone( java.util.TimeZone.getTimeZone( "Asia/Taipei" ) );
        System.out.println( sdf.format(date) );  // "2018-05-14T17:23:30.316+08:00"

參考:
Convert Date to String in Java · Mincong HUANG
 

字串樣式:

  • "00-00"
        str.matches("\\d{2}-\\d{2}")
        java.util.regex.Pattern p =  java.util.regex.Pattern.compile("\\d{2}-\\d{2}");
        p.matcher(str).matches();
  • 字串中是否有時間
        String string = "hi there 2:15" ;
        System.out.println( String.format("Is there a time in here:(%1$s)", string) );
        java.util.regex.Pattern p = java.util.regex.Pattern.compile( ".*([01]?[0-9]|2[0-3]):[0-5][0-9].*" );
        java.util.regex.Matcher m = p.matcher( string );
        if ( m.matches() ) {
            System.out.println( "Yes" );
        } else {
            System.out.println( "No." );
        }
        // "Is there a time in here:(hi there 2:15)"
        // "Yes"

參考:
java - How to check if a string matches a specific format? - Stack Overflow
java - How do I check if there's a time inside a string? - Stack Overflow
尚未引用:
java - How to check if string matches date pattern using time API? - Stack Overflow
線上測試正則表示式
Online regex tester and debugger: PHP, PCRE, Python, Golang and JavaScript
 

 

 

Java 8

  • java.time.Instant
        "如果您正使用 Java 8,不要再用 java.util.Date 了。 除非是從函式庫裡取得的 java.util.Date 物件,您無法控制的。"
    • java.time.Instant
          java.time.Instant inst = java.time.Instant.now();
          System.out.println( inst );  // "2018-05-08T08:09:25.432Z"
    • java.util.Date -> java.time.Instant
          java.util.Date utilDate = new java.util.Date();
          java.time.Instant inst = utilDate.toInstant();
          System.out.println( utilDate );  // "Tue May 08 16:09:25 GMT+08:00 2018"
          System.out.println( inst );  // "2018-05-08T08:09:25.513Z"
      
    • java.sql.Timestamp -> java.time.Instant
          java.sql.Timestamp sqlTstp = new java.sql.Timestamp( System.currentTimeMillis() );
          java.time.Instant inst = sqlTstp.toInstant();
          System.out.println( sqlTstp );  // "2018-05-15 10:23:23.749"
          System.out.println( inst );  // "2018-05-15T02:23:23.749Z"
    • java.time.Instant -> java.sql.Timestamp
          java.time.Instant inst = java.time.Instant.now();
          java.sql.Timestamp sqlTstp = java.sql.Timestamp.from( inst );
          System.out.println( inst );  // "2018-05-15T02:30:27.005Z"
          System.out.println( sqlTstp );  // "2018-05-15 10:30:27.005"
    • java.time.Instant -> java.time.LocalDateTime
          java.time.Instant inst = java.time.Instant.now();
          java.time.LocalDateTime ldt = inst.atOffset( java.time.ZoneOffset.UTC ).toLocalDateTime();
          System.out.println( inst );  // "2018-05-08T08:09:25.529Z"
          System.out.println( ldt );  // "2018-05-08T08:09:25.529"
    • String
       
       
  • java.time.LocalDateTime is a date-time without a time-zone
        java.time.LocalDateTime ldt = java.time.LocalDateTime.now();
        java.time.format.DateTimeFormatter fmt = java.time.format.DateTimeFormatter.ofPattern( "yyyy-MM-dd'T'HH:mm:ss" );
        System.out.println( ldt.format(fmt) );  // "2018-05-08T16:33:31"
        System.out.println( ldt.format(java.time.format.DateTimeFormatter.ISO_LOCAL_DATE_TIME) );  // "2018-05-08T16:33:31.163"
    
     
  • java.time.ZonedDateTime
        java.time.ZoneId taipeiZone = java.time.ZoneId.of( "Asia/Taipei" ) ;
        java.time.ZonedDateTime zoneDT = java.time.LocalDate.of( 2017, 2, 16 )
                                                              .atTime( 20, 22, 28 )
                                                              .atZone( taipeiZone );
        java.time.format.DateTimeFormatter dtFormat = java.time.format.DateTimeFormatter.ofPattern( "yyyy-MM-dd'T'HH:mm:ss.SSSXXX" );
        String dtStr = zoneDT.format( dtFormat );
        System.out.println( zoneDT );  // "2017-02-16T20:22:28+08:00[Asia/Taipei]"
        System.out.println( dtStr );  // "2017-02-16T20:22:28.000+08:00"
  • java.time.ZoneId
     
  • java.time.ZoneOffset
     
    • java.time.ZoneId -> java.time.ZoneOffset
          java.time.Instant inst = java.time.Instant.now();  // can be LocalDateTime
          java.time.ZoneId myZoneId = java.time.ZoneId.systemDefault();  // my timezone
          java.time.ZoneOffset myZoneOffset = myZoneId.getRules().getOffset( inst );
          System.out.println( inst );  // "2018-05-15T03:23:44.909Z"
          System.out.println( myZoneId );  // "GMT+08:00"
          System.out.println( myZoneOffset );  // "+08:00"
       
  • java.time.format.DateTimeFormatter
        java.time.format.DateTimeFormatter dtFormat = java.time.format.DateTimeFormatter.ofPattern( "yyyyMMdd HH:mm:ss.SSSSSS Z" );
        java.time.ZonedDateTime zoneDT = java.time.ZonedDateTime.now();
        String dtStr = zoneDT.format( dtFormat );
        System.out.println( zoneDT );  // "2018-05-15T13:38:57.250+08:00[GMT+08:00]"
        System.out.println( dtStr );  // "20180515 13:38:57.250000 +0800"

 

參考:
How to get and set specified time in java.time.Instant? - Stack Overflow
datetime - java.util.date to String using DateTimeFormatter - Stack Overflow
Java Date Time - LocalDateTime now() example
Is there any way to convert ZoneId to ZoneOffset in java 8? - Stack Overflow
java - Format LocalDateTime with Timezone in Java8 - Stack Overflow
尚未引用:
The Current Date, Time and Timestamp in Java 8 | Baeldung
Java8 日期/時間(Date Time)API指南-趣讀
 

 

Joda-Time

API doc 
"如果您使用 java 8,優先使用 java.time,因為它比 Joda-Time 乾淨多了。"

取得現在時間,"toString()"結果:

  • org.joda.time.DateTime
        org.joda.time.DateTime dt = new org.joda.time.DateTime();
        System.out.println( dt );  // "2018-05-14T17:56:53.687+08:00"
  •  
     

轉換:

  • java.util.date -> org.joda.time.DateTime
        java.util.Date utilDate = new java.util.Date();
        org.joda.time.DateTime dt = new org.joda.time.DateTime( utilDate );
        System.out.println( utilDate );  // "Tue May 15 13:20:15 GMT+08:00 2018"
        System.out.println( dt );  // "2018-05-15T13:20:15.472+08:00"
  •  
     

計算:

  • 相隔幾天
        org.joda.time.DateTime dt1 = new org.joda.time.DateTime( 2017, 1, 1, 0, 0, 0, 0 );
        org.joda.time.DateTime dt2 = new org.joda.time.DateTime( 2018, 1, 1, 0, 0, 0, 0 );
        int days = org.joda.time.Days.daysBetween( dt1, dt2 ).getDays();
        System.out.println( days );  // "365"
        org.joda.time.DateTime dt1 = new org.joda.time.DateTime( 2020, 1, 1, 0, 0, 0, 0 );
        org.joda.time.DateTime dt2 = new org.joda.time.DateTime( 2021, 1, 1, 0, 0, 0, 0 );
        int days = org.joda.time.Days.daysBetween( dt1, dt2 ).getDays();
        System.out.println( days );  // "366"
  •  

 

參考:
Should I use Java date and time classes or go with a 3rd party library like Joda Time? - Stack Overflow
Joda-Time – Quick start guide
date - Java: getMinutes and getHours - Stack Overflow
datetime - Convert from java.util.date to JodaTime - Stack Overflow
datetime - How do you subtract Dates in Java? - Stack Overflow
 

 

 

線上工具:
Long time 轉換
Epoch Converter - Unix Timestamp Converter
 

 

 

文章標籤
創作者介紹
創作者 Robert 的頭像
Robert

Robert 的部落格

Robert 發表在 痞客邦 留言(0) 人氣()