Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Java Date and Time

Java Date and Time

Java provides multiple sets of Date and Time APIs. The following is a comparison of the main categories and a summary of commonly used methods:

Category Main classes Thread Safety Mutability Java Version Feature
Traditional Date Date, Calendar, GregorianCalendar No Mutable 1.0+ Many design flaws; not recommended for use
New Date and Time LocalDate, LocalTime, LocalDateTime, ZonedDateTime, ChronoUnit Is Immutable 8+ Well-designed; recommended for use
Timestamp Instant Is Immutable 8+ Machine time, accurate to nanoseconds
Formatting DateTimeFormatter Is Immutable 8+ Thread-safe formatting class

LocalDate/DateTimeFormatter

LocalDate/DateTimeFormatter are date classes introduced in Java 8. LocalDate is used to represent a date without time (year-month-day), and DateTimeFormatter is used to format and parse date-time objects.

Example

import

java.time.LocalDate

;

import

java.time.format.DateTimeFormatter

;

public

class

RunoobTest

{

   

public

static

void

main

(

String

[

]

args

)

{

       

// Get current date

        LocalDate today

=

LocalDate.

now

(

)

;

       

System

.

out

.

println

(

"Current date: "

today

)

;

       

       

// Create a specific date

        LocalDate nationalDay

=

LocalDate.

of

(

2025

,

10

,

1

)

;

       

System

.

out

.

println

(

"National Day: "

nationalDay

)

;

       

       

// Date addition and subtraction

        LocalDate tomorrow

=

today.

plusDays

(

1

)

;

        LocalDate nextMonth

=

today.

plusMonths

(

1

)

;

        LocalDate lastYear

=

today.

minusYears

(

1

)

;

       

       

System

.

out

.

println

(

"Tomorrow: "

tomorrow

)

;

       

System

.

out

.

println

(

"Next month: "

nextMonth

)

;

       

System

.

out

.

println

(

"Same day last year: "

lastYear

)

;

   

}

}

The output of the above example is:

当前日期: 2025-05-01
国庆节: 2025-10-01
明天: 2025-05-02
下个月: 2025-06-01
去年今天: 2024-05-01
  1. For new projects, prioritize using the java.time package (Java 8+)

  2. Avoid using the outdated Date and Calendar classes

  3. Clearly distinguish whether a time zone is needed:

  4. No time zone needed: LocalDate/LocalTime/LocalDateTime

  5. Time zone needed: ZonedDateTime

  6. -

    No time zone needed: LocalDate/LocalTime/LocalDateTime

    -

    Time zone needed: ZonedDateTime

    1. Consider thread safety when formatting: Use DateTimeFormatter instead of SimpleDateFormat

    2. Database Interaction:

    3. JDBC 4.2+ directly supports java.time types

    4. Older versions can be converted to java.sql.Date/Timestamp

    5. -

      JDBC 4.2+ directly supports java.time types

      -

      Older versions can be converted to java.sql.Date/Timestamp

      ** 1. LocalDate (Date)**

      Example

      LocalDate today

      =

      LocalDate.

      now

      (

      )

      ;

      LocalDate date

      =

      LocalDate.

      of

      (

      2023

      , Month.

      JUNE

      ,

      15

      )

      ;

      int

      year

      =

      date.

      getYear

      (

      )

      ;

       

      // 2023

      Month month

      =

      date.

      getMonth

      (

      )

      ;

       

      // JUNE

      int

      day

      =

      date.

      getDayOfMonth

      (

      )

      ;

       

      // 15

      LocalDate nextWeek

      =

      today.

      plusWeeks

      (

      1

      )

      ;

      boolean

      isLeap

      =

      date.

      isLeapYear

      (

      )

      ;

       

      // Check for leap year

      2. LocalTime (Time)

      Example

      LocalTime now

      =

      LocalTime.

      now

      (

      )

      ;

      LocalTime time

      =

      LocalTime.

      of

      (

      14

      ,

      30

      ,

      45

      )

      ;

       

      // 14:30:45

      int

      hour

      =

      time.

      getHour

      (

      )

      ;

       

      // 14

      int

      minute

      =

      time.

      getMinute

      (

      )

      ;

       

      // 30

      LocalTime nextHour

      =

      time.

      plusHours

      (

      1

      )

      ;

      3. LocalDateTime (Date and Time)

      Example

      LocalDateTime ldt

      =

      LocalDateTime.

      now

      (

      )

      ;

      LocalDateTime dt

      =

      LocalDateTime.

      of

      (

      2023

      ,

      6

      ,

      15

      ,

      14

      ,

      30

      )

      ;

      LocalDateTime nextMonth

      =

      dt.

      plusMonths

      (

      1

      )

      ;

      4. ZonedDateTime (Date and Time with Time Zone)

      Example

      ZonedDateTime zdt

      =

      ZonedDateTime.

      now

      (

      ZoneId.

      of

      (

      "Asia/Shanghai"

      )

      )

      ;

      ZonedDateTime nyTime

      =

      zdt.

      withZoneSameInstant

      (

      ZoneId.

      of

      (

      "America/New_York"

      )

      )

      ;

      ZoneId zone

      =

      zdt.

      getZone

      (

      )

      ;

       

      // Get time zone

      5. Instant (Timestamp)

      Example

      Instant now

      =

      Instant.

      now

      (

      )

      ;

       

      // Get current timestamp

      Instant later

      =

      now.

      plusSeconds

      (

      60

      )

      ;

       

      // 60 seconds later

      long

      epochMilli

      =

      now.

      toEpochMilli

      (

      )

      ;

       

      // Get millisecond timestamp


      Date Class

      The java.util package provides the Date class to encapsulate the current date and time. The Date class provides two constructors to instantiate Date objects.

      The first constructor uses the current date and time to initialize the object.

      Date

      (

      )

      The second constructor accepts a parameter that is the number of milliseconds since January 1, 1970.

      Date

      (

      long

      millisec

      )

      After a Date object is created, the following methods can be called.

      No. Method and Description
      1 boolean after(Date date)
      Returns true if the Date object on which this method is called is after the specified date; otherwise returns false.
      2 boolean before(Date date)
      Returns true if the Date object on which this method is called is before the specified date; otherwise returns false.
      3 Object clone( )
      Returns a copy of this object.
      4 int compareTo(Date date)
      Compares the Date object on which this method is called with the specified date. Returns 0 when they are equal, a negative number when the calling object is before the specified date, and a positive number when it is after.
      5 int compareTo(Object obj)
      If obj is of type Date, the operation is equivalent to compareTo(Date). Otherwise it throws ClassCastException.
      6 boolean equals(Object date)
      Returns true when the Date object on which this method is called equals the specified date; otherwise returns false.
      7 long getTime( )
      Returns the number of milliseconds since 00:00:00 GMT on January 1, 1970, represented by this Date object.
      8 int hashCode( )
       Returns the hash code value of this object.
      9 void setTime(long time)
               
       用自1970年1月1日00:00:00 GMT以后time毫秒数设置时间和日期。 |
      

      | 10 | String toString( )
      Converts this Date object into a String in the following form: dow mon dd hh:mm:ss zzz yyyy where: dow is a day of the week (Sun, Mon, Tue, Wed, Thu, Fri, Sat). |


      Get Current Date and Time

      Getting the current date and time in Java is simple: use the Date object's toString() method to print the current date and time, as shown below:

      Example

      import

      java

      .

      util

      .

      Date

      ;

      public

      class

      DateDemo

      {

      public

      static

      void

      main

      (

      String

      [

      ]

      args

      )

      {

      //

      Initialize the Date object

      Date

      date

      =

      new

      Date

      (

      )

      ;

      //

      Use the toString() function to display the date and time

      System

      .

      out

      .

      println

      (

      date

      .

      toString

      (

      )

      )

      ;

      }

      }

      Run Example »

      The compilation and execution results of the above example are as follows:

      
      Mon May 04 09:51:52 CDT 2013
      

      Date Comparison

      Java uses the following three methods to compare two dates:

      1. Comparing Using the getTime() Method

      This method works by comparing the number of milliseconds since January 1, 1970 (the Unix epoch) of the date objects.

      Example

      import

      java.util.Date

      ;

      public

      class

      DateComparison

      {

         

      public

      static

      void

      main

      (

      String

      [

      ]

      args

      )

      {

             

      Date

      date1

      =

      new

      Date

      (

      121

      ,

      5

      ,

      15

      )

      ;

      // June 15, 2021

             

      Date

      date2

      =

      new

      Date

      (

      121

      ,

      5

      ,

      20

      )

      ;

      // June 20, 2021

             

             

      // Compare milliseconds

             

      if

      (

      date1.

      getTime

      (

      )

      <

      date2.

      getTime

      (

      )

      )

      {

                 

      System

      .

      out

      .

      println

      (

      "date1 is before date2"

      )

      ;

             

      }

      else

      if

      (

      date1.

      getTime

      (

      )

      date2.

      getTime

      (

      )

      )

      {

                 

      System

      .

      out

      .

      println

      (

      "date1 is after date2"

      )

      ;

             

      }

      else

      {

                 

      System

      .

      out

      .

      println

      (

      "The two dates are the same"

      )

      ;

             

      }

         

      }

      }

      Output:

      date1 在 date2 之前
      

      2. Using the before(), after(), and equals() Methods

      These comparison methods are built into the Date class and have clearer semantics.

      Example

      import

      java.util.Date

      ;

      public

      class

      DateComparison

      {

         

      public

      static

      void

      main

      (

      String

      [

      ]

      args

      )

      {

             

      Date

      date1

      =

      new

      Date

      (

      121

      ,

      5

      ,

      15

      )

      ;

      // June 15, 2021

             

      Date

      date2

      =

      new

      Date

      (

      121

      ,

      5

      ,

      20

      )

      ;

      // June 20, 2021

             

             

      // Use the before() method

             

      System

      .

      out

      .

      println

      (

      "Is date1 before date2? "

      date1.

      before

      (

      date2

      )

      )

      ;

             

             

      // Use the after() method

             

      System

      .

      out

      .

      println

      (

      "Is date1 after date2? "

      date1.

      after

      (

      date2

      )

      )

      ;

             

             

      // Use the equals() method

             

      System

      .

      out

      .

      println

      (

      "Are the two dates the same? "

      date1.

      equals

      (

      date2

      )

      )

      ;

         

      }

      }

      Output:

      date1 在 date2 之前吗? true
      date1 在 date2 之后吗? false
      两个日期相同吗? false
      

      3. Using the compareTo() Method

      The Date class implements the Comparable interface, so the compareTo() method can be used for comparison.

      Example

      import

      java.util.Date

      ;

      public

      class

      DateComparison

      {

         

      public

      static

      void

      main

      (

      String

      [

      ]

      args

      )

      {

             

      Date

      date1

      =

      new

      Date

      (

      121

      ,

      5

      ,

      15

      )

      ;

      // June 15, 2021

             

      Date

      date2

      =

      new

      Date

      (

      121

      ,

      5

      ,

      20

      )

      ;

      // June 20, 2021

             

             

      int

      result

      =

      date1.

      compareTo

      (

      date2

      )

      ;

             

             

      if

      (

      result

      <
      0
      )
      {
      System

      .

      out

      .

      println

      (

      "date1 is before date2"

      )

      ;

             

      }

      else

      if

      (

      result

      0

      )

      {

                 

      System

      .

      out

      .

      println

      (

      "date1 is after date2"

      )

      ;

             

      }

      else

      {

                 

      System

      .

      out

      .

      println

      (

      "The two dates are the same"

      )

      ;

             

      }

         

      }

      }

      Output:

      
      date1 在 date2 之前
      

      Formatting Dates with SimpleDateFormat

      SimpleDateFormat is a class for formatting and parsing dates in a locale-sensitive manner. SimpleDateFormat allows you to choose any user-defined date-time format to work with. For example:

      Example

      import

      java

      .

      util

      .*;

      import

      java

      .

      text

      .*;

      public

      class

      DateDemo

      {

      public

      static

      void

      main

      (

      String

      [

      ]

      args

      )

      {

      Date

      dNow

      =

      new

      Date

      (

      )

      ;

      SimpleDateFormat

      ft

      =

      new

      SimpleDateFormat

      (

      "

      yyyy-MM-dd hh:mm:ss

      "

      )

      ;

      System

      .

      out

      .

      println

      (

      "

      Current time is:

      "

      ft

      .

      format

      (

      dNow

      )

      )

      ;

      }

      }

      Run Example »

      
      SimpleDateFormat ft = new SimpleDateFormat ("yyyy-MM-dd hh:mm:ss");
      

      This line of code establishes the conversion format, where yyyy is the full calendar year, MM is the month, dd is the day, and HH:mm:ss are the hour, minute, and second.

      Note: Some format letters are uppercase and some are lowercase. For example, MM is the month, mm is the minute; HH is the 24-hour format, while hh is the 12-hour format.

      The compilation and execution results of the above example are as follows:

      
      当前时间为: 2018-09-06 10:16:34
      

      Formatting Codes for Date and Time

      A time pattern string is used to specify the time format. In this pattern, all ASCII letters are reserved as pattern letters, defined as follows:

      Common Format Patterns Description Example
      G Era marker AD
      y Four-digit year 2001
      M Month July or 07
      d Day of the month 10
      h  Hour in A.M./P.M. (1~12) format 12
      H Hour of the day (0~23) 22
      m Minutes 30
      s Seconds 55
      S Milliseconds 234
      E Day of week Tuesday
      D Day of the year 360
      F Day of the week within a month 2 (second Wed. in July)
      w Week of the year 40
      W Week of the month 1
      a A.M./P.M. marker PM
      k Hour of the day (1~24) 24
      K  Hour in A.M./P.M. (0~11) format 10
      z Timezone Eastern Standard Time
      ' Text delimiter Delimiter
      " Single quote `

      Formatting Dates with printf

      The printf method can easily format time and date. Using a two-letter format, it starts with %t and ends with one of the letters in the table below.

      Conversion Specifier

      Description

      Example

      %tc

      Includes all date and time information

      Saturday October 27 14:21:20 CST 2007

      %tF

      "year-month-day" format

      2007-10-27

      %tD

      "month/day/year" format

      10/27/07

      %tr

      "HH:MM:SS PM" format (12-hour clock)

      02:25:51 PM

      %tT

      "HH:MM:SS" format (24-hour clock)

      14:28:16

      %tR

      "HH:MM" format (24-hour clock)

      14:28

      More printf For parsing, see:Java Formatted Output printf Example

      Example

      Example

      import

      java.util.Date

      ;

      public

      class

      DateFormatExample

      {

         

      public

      static

      void

      main

      (

      String

      [

      ]

      args

      )

      {

           

      Date

      date

      =

      new

      Date

      (

      )

      ;

           

      System

      .

      out

      .

      printf

      (

      "%tY-%tm-%td %tH:%tM:%tS %tZ"

      , date, date, date, date, date, date, date

      )

      ;

         

      }

      }

      The execution output is:

      2023-02-24 13:34:45 GMT+08:00
      

      Example

      import

      java

      .

      util

      .

      Date

      ;

      public

      class

      DateDemo

      {

      public

      static

      void

      main

      (

      String

      [

      ]

      args

      )

      {

      //

      Initialize the Date object

      Date

      date

      =

      new

      Date

      (

      )

      ;

      //

      Usage of c

      System

      .

      out

      .

      printf

      (

      "

      All date and time information: %tc%n

      "

      ,

      date

      )

      ;

      //

      Usage of f

      System

      .

      out

      .

      printf

      (

      "

      Year-month-day format: %tF%n

      "

      ,

      date

      )

      ;

      //

      Usage of d

      System

      .

      out

      .

      printf

      (

      "

      Month/day/year format: %tD%n

      "

      ,

      date

      )

      ;

      //

      Usage of r

      System

      .

      out

      .

      printf

      (

      "

      HH:MM:SS PM format (12-hour clock): %tr%n

      "

      ,

      date

      )

      ;

      //

      Usage of t

      System

      .

      out

      .

      printf

      (

      "

      HH:MM:SS format (24-hour clock): %tT%n

      "

      ,

      date

      )

      ;

      //

      Usage of R

      System

      .

      out

      .

      printf

      (

      "

      HH:MM format (24-hour clock): %tR

      "

      ,

      date

      )

      ;

      }

      }

      The compilation and execution results of the above example are as follows:

      
      全部日期和时间信息:星期一 九月 10 10:43:36 CST 2012  
      年-月-日格式:2012-09-10  
      月/日/年格式:09/10/12  
      HH:MM:SS PM格式(12时制):10:43:36 上午  
      HH:MM:SS格式(24时制):10:43:36  
      HH:MM格式(24时制):10:43  
      

      If you need to provide the date repeatedly, formatting each part this way becomes a bit complicated. Therefore, you can use a format string to indicate the index of the argument to be formatted.

      The index must immediately follow % and must end with $. For example:

      Example

      import

      java

      .

      util

      .

      Date

      ;

      public

      class

      DateDemo

      {

      public

      static

      void

      main

      (

      String

      [

      ]

      args

      )

      {

      //

      Initialize the Date object

      Date

      date

      =

      new

      Date

      (

      )

      ;

      //

      Displaying Date and Time with toString()

      System

      .

      out

      .

      printf

      (

      "

      %1$s %2$tB %2$td, %2$tY

      "

      ,

      "

      Due date:

      "

      ,

      date

      )

      ;

      }

      }

      Run Example »

      The compilation and execution results of the above example are as follows:

      
      Due date: February 09, 2014
      

      Alternatively, you can use < flag. It indicates that the previously formatted argument is to be used again. For example:

      Example

      import

      java

      .

      util

      .

      Date

      ;

      public

      class

      DateDemo

      {

      public

      static

      void

      main

      (

      String

      [

      ]

      args

      )

      {

      //

      Initialize the Date object

      Date

      date

      =

      new

      Date

      (

      )

      ;

      //

      Display formatted time

      System

      .

      out

      .

      printf

      (

      "

      %s %tB %

      "

      ,

      "

      Due date:

      "

      ,

      date

      )

      ;

      }

      }

      Run Example »

      The compilation and execution results of the above example are as follows:

      
      Due date: February 09, 2014
      

      Defining conversion specifiers for date formats allows dates to be turned into new strings via the specified specifiers. These date conversion specifiers are as follows:

      Example

      import

      java

      .

      util

      .*;

      public

      class

      DateDemo

      {

      public

      static

      void

      main

      (

      String

      [

      ]

      args

      )

      {

      Date

      date

      =

      new

      Date

      (

      )

      ;

      //

      Usage of b, abbreviated month name

      String

      str

      =

      String

      .

      format

      (

      Locale

      .

      US

      ,

      "

      Abbreviated English month name: %tb

      "

      ,

      date

      )

      ;

      System

      .

      out

      .

      println

      (

      str

      )

      ;

      System

      .

      out

      .

      printf

      (

      "

      Localized abbreviated month name: %tb%n

      "

      ,

      date

      )

      ;

      //

      Usage of B, full month name

      str

      =

      String

      .

      format

      (

      Locale

      .

      US

      ,

      "

      Full English month name: %tB

      "

      ,

      date

      )

      ;

      System

      .

      out

      .

      println

      (

      str

      )

      ;

      System

      .

      out

      .

      printf

      (

      "

      Localized full month name: %tB%n

      "

      ,

      date

      )

      ;

      //

      Usage of a, abbreviated weekday name

      str

      =

      String

      .

      format

      (

      Locale

      .

      US

      ,

      "

      Abbreviated English weekday name: %ta

      "

      ,

      date

      )

      ;

      System

      .

      out

      .

      println

      (

      str

      )

      ;

      //

      Usage of A, full weekday name

      System

      .

      out

      .

      printf

      (

      "

      Localized abbreviated weekday name: %tA%n

      "

      ,

      date

      )

      ;

      //

      Usage of C, first two digits of the year

      System

      .

      out

      .

      printf

      (

      "

      First two digits of the year (padded with 0 if fewer than two digits): %tC%n

      "

      ,

      date

      )

      ;

      //

      Usage of y, last two digits of the year

      System

      .

      out

      .

      printf

      (

      "

      Last two digits of the year (padded with 0 if fewer than two digits): %ty%n

      "

      ,

      date

      )

      ;

      //

      Usage of j, day of the year

      System

      .

      out

      .

      printf

      (

      "

      Day of the year (i.e., the nth day of the year): %tj%n

      "

      ,

      date

      )

      ;

      //

      Usage of m, month

      System

      .

      out

      .

      printf

      (

      "

      Two-digit month (padded with 0 if fewer than two digits): %tm%n

      "

      ,

      date

      )

      ;

      //

      Usage of d, day (two digits, padded with zero if needed)

      System

      .

      out

      .

      printf

      (

      "

      Two-digit day (padded with 0 if fewer than two digits): %td%n

      "

      ,

      date

      )

      ;

      //

      Usage of e, day (one digit, not padded with zero)

      System

      .

      out

      .

      printf

      (

      "

      Day of the month (not padded with 0 in front): %te

      "

      ,

      date

      )

      ;

      }

      }

      The output is:

      
      英文月份简称:May
      本地月份简称:五月
      英文月份全称:May
      本地月份全称:五月
      英文星期的简称:Thu
      本地星期的简称:星期四
      年的前两位数字(不足两位前面补0):20
      年的后两位数字(不足两位前面补0):17
      一年中的天数(即年的第几天):124
      两位数字的月份(不足两位前面补0):05
      两位数字的日(不足两位前面补0):04
      月份的日(前面不补0):4
      

      Parsing a String into a Time

      The SimpleDateFormat class has some additional methods, notably parse(), which attempts to parse a string according to the format stored in the given SimpleDateFormat object. For example:

      Example

      import

      java

      .

      util

      .*;

      import

      java

      .

      text

      .*;

      public

      class

      DateDemo

      {

      public

      static

      void

      main

      (

      String

      [

      ]

      args

      )

      {

      SimpleDateFormat

      ft

      =

      new

      SimpleDateFormat

      (

      "

      yyyy-MM-dd

      "

      )

      ;

      String

      input

      =

      args

      .

      length

      ==

      0

      ?

      "

      1818-11-11

      "

      :

      args

      [

      0

      ]

      ;

      System

      .

      out

      .

      print

      (

      input

      "

      Parses as

      "

      )

      ;

      Date

      t

      ;

      try

      {

      t

      =

      ft

      .

      parse

      (

      input

      )

      ;

      System

      .

      out

      .

      println

      (

      t

      )

      ;

      }

      catch

      (

      ParseException

      e

      )

      {

      System

      .

      out

      .

      println

      (

      "

      Unparseable using

      "

      ft

      )

      ;

      }

      }

      }

      Run Example »

      The compilation and execution results of the above example are as follows:

      
      $ java DateDemo
      1818-11-11 Parses as Wed Nov 11 00:00:00 GMT 1818
      $ java DateDemo 2007-12-01
      2007-12-01 Parses as Sat Dec 01 00:00:00 GMT 2007
      

      Java Sleep

      sleep() puts the current thread into a stalled state (blocking the current thread), yielding CPU usage, so that the current thread does not monopolize the CPU resources obtained by the process, leaving time for other threads to execute.

      You can make the program sleep for as little as one millisecond or for any length of time up to the lifetime of your computer. For example, the following program sleeps for 3 seconds:

      Example

      import

      java

      .

      util

      .*;

      public

      class

      SleepDemo

      {

      public

      static

      void

      main

      (

      String

      [

      ]

      args

      )

      {

      try

      {

      System

      .

      out

      .

      println

      (

      new

      Date

      (

      )

      "

      \n

      "

      )

      ;

      Thread

      .

      sleep

      (

      1000

      3

      )

      ;

      //

      Sleep for 3 seconds

      System

      .

      out

      .

      println

      (

      new

      Date

      (

      )

      "

      \n

      "

      )

      ;

      }

      catch

      (

      Exception

      e

      )

      {

      System

      .

      out

      .

      println

      (

      "

      Got an exception!

      "

      )

      ;

      }

      }

      }

      Run Example »

      The compilation and execution results of the above example are as follows:

      
      Thu Sep 17 10:20:30 CST 2015
      
      Thu Sep 17 10:20:33 CST 2015
      

      Measuring Time

      The following example shows how to measure a time interval (in milliseconds):

      Example

      import

      java

      .

      util

      .*;

      public

      class

      DiffDemo

      {

      public

      static

      void

      main

      (

      String

      [

      ]

      args

      )

      {

      try

      {

      long

      start

      =

      System

      .

      currentTimeMillis

      (

      )

      ;

      System

      .

      out

      .

      println

      (

      new

      Date

      (

      )

      "

      \n

      "

      )

      ;

      Thread

      .

      sleep

      (

      5

      60

      10

      )

      ;

      System

      .

      out

      .

      println

      (

      new

      Date

      (

      )

      "

      \n

      "

      )

      ;

      long

      end

      =

      System

      .

      currentTimeMillis

      (

      )

      ;

      long

      diff

      =

      end

      start

      ;

      System

      .

      out

      .

      println

      (

      "

      Difference is :

      "

      diff

      )

      ;

      }

      catch

      (

      Exception

      e

      )

      {

      System

      .

      out

      .

      println

      (

      "

      Got an exception!

      "

      )

      ;

      }

      }

      }

      Run Example »

      The compilation and execution results of the above example are as follows:

      
      Fri Jan 08 09:48:47 CST 2016
      
      Fri Jan 08 09:48:50 CST 2016
      
      Difference is : 3019
      

      Calendar Class

      We can now format and create a date object, but how can we set and get specific parts of the date data, such as the hour, day, or minute? And how do we add or subtract values from those parts? The answer is to use the Calendar class.

      The Calendar class is much more powerful than the Date class and is also a bit more complex in its implementation.

      The Calendar class is an abstract class. In actual use, objects of specific subclasses are instantiated; the object creation process is transparent to the programmer and only requires calling the getInstance method.

      Create a Calendar object representing the system's current date

      
      Calendar c = Calendar.getInstance();//默认是当前日期
      

      Create a Calendar object for a specified date

      To represent a specific time using the Calendar class, you first need to create a Calendar object and then set the year, month, and day parameters in that object.

      
      //Create a Calendar object representing June 12, 2009
      Calendar c1 = Calendar.getInstance();
      c1.set(2009, 6 - 1, 12);
      

      Calendar Class Field Types

      The Calendar class uses the following constants to represent different meanings; in fact, many classes within the JDK adopt this idea

      Constant Description
      Calendar.YEAR Year
      Calendar.MONTH Month
      Calendar.DATE Date
      Calendar.DAY_OF_MONTH Date, with exactly the same meaning as the field above
      Calendar.HOUR Hour (12-hour)
      Calendar.HOUR_OF_DAY Hour (24-hour)
      Calendar.MINUTE Minute
      Calendar.SECOND Second
      Calendar.DAY_OF_WEEK Day of week

      Setting Calendar Class Object Information

      Set configuration

      For example:

      Calendar c1 = Calendar.getInstance();
      

      Call:

      
      public final void set(int year,int month,int date)
      
      
      c1.set(2009, 6, 12);//把Calendar对象c1的年月日分别设这为:2009、6、12
      

      Set using field types

      If you only want to set a certain field, such as the day value, you can use the set method as follows:

      public void set(int field,int value)
      

      Set the date represented by the c1 object to the 10th; all other values will be recalculated

      
      c1.set(Calendar.DATE,10);
      

      Set the year represented by the c1 object to 2008; all other values will be recalculated

      
      c1.set(Calendar.YEAR,2008);
      

      The meaning of set for other field attributes follows by analogy

      Add configuration

      
      Calendar c1 = Calendar.getInstance();
      

      Add 10 to the date of the c1 object, meaning c1 now represents the date 10 days later; all other values will be recalculated

      
      c1.add(Calendar.DATE, 10);
      

      Subtract 10 from the date of the c1 object, meaning c1 now represents the date 10 days earlier; all other values will be recalculated

      c1.add(Calendar.DATE, -10);
      

      The meaning of add for other field attributes follows by analogy

      Obtaining Calendar Class Object Information

      Calendar

      c1

      =

      Calendar

      .

      getInstance

      (

      )

      ;

      //

      Get the year

      int

      year

      =

      c1

      .

      get

      (

      Calendar

      .

      YEAR

      )

      ;

      //

      Get the month

      int

      month

      =

      c1

      .

      get

      (

      Calendar

      .

      MONTH

      )

      1

      ;

      //

      Get the date

      int

      date

      =

      c1

      .

      get

      (

      Calendar

      .

      DATE

      )

      ;

      //

      Get the hour

      int

      hour

      =

      c1

      .

      get

      (

      Calendar

      .

      HOUR_OF_DAY

      )

      ;

      //

      Get the minutes

      int

      minute

      =

      c1

      .

      get

      (

      Calendar

      .

      MINUTE

      )

      ;

      //

      Get the seconds

      int

      second

      =

      c1

      .

      get

      (

      Calendar

      .

      SECOND

      )

      ;

      //

      Get the day of the week (note: this differs from the Date class — 1 represents Sunday, 2 represents Monday, 3 represents Tuesday, and so on)

      int

      day

      =

      c1

      .

      get

      (

      Calendar

      .

      DAY_OF_WEEK

      )

      ;


      GregorianCalendar Class

      The Calendar class implements the Gregorian calendar, and GregorianCalendar is a concrete implementation of the Calendar class.

      The Calendar getInstance() method returns a GregorianCalendar object initialized by default with the current locale and time zone. GregorianCalendar defines two fields: AD and BC. These represent the two eras defined by the Gregorian calendar.

      The following lists several constructors of the GregorianCalendar object:

      No. Constructor and Description
      1 **GregorianCalendar() **
      Constructs a default GregorianCalendar using the current time in the default time zone with the default locale.
      2 **GregorianCalendar(int year, int month, int date) **
      Constructs a GregorianCalendar with the given date settings in the default time zone with the default locale
      3 **GregorianCalendar(int year, int month, int date, int hour, int minute) **
      Constructs a GregorianCalendar with the given date and time settings for the default time zone with the default locale.
      4 **GregorianCalendar(int year, int month, int date, int hour, int minute, int second) **
        Constructs a GregorianCalendar with the given date and time settings for the default time zone with the default locale.
      5 **GregorianCalendar(Locale aLocale) **
      Constructs a GregorianCalendar based on the current time in the default time zone with the given locale.
      6 **GregorianCalendar(TimeZone zone) **
      Constructs a GregorianCalendar based on the current time in the given time zone with the default locale.
      7 **GregorianCalendar(TimeZone zone, Locale aLocale) **
       Constructs a GregorianCalendar based on the current time in the given time zone with the given locale.

      The following is a list of some useful methods provided by the GregorianCalendar class:

      No. Method and Description
      1 **void add(int field, int amount) **
      Adds the specified (signed) amount of time to the given calendar field according to calendar rules.
      2 **protected void computeFields() **
      Converts UTC millisecond values to time field values
      3 **protected void computeTime() **
      Overrides Calendar, converting time field values to UTC millisecond values
      4 **boolean equals(Object obj) **
      Compares this GregorianCalendar with the specified Object.
      5 **int get(int field) **
      Gets the time value of the specified field
      6 **int getActualMaximum(int field) **
      Returns the maximum value of the given field for the current date
      7 **int getActualMinimum(int field) **
      Returns the minimum value of the given field for the current date
      8 **int getGreatestMinimum(int field) **
       Returns the highest minimum value of the given calendar field for this GregorianCalendar instance.
      9 **Date getGregorianChange() **
      Gets the Gregorian calendar change date.
      10 **int getLeastMaximum(int field) **
      Returns the lowest maximum value of the given calendar field for this GregorianCalendar instance
      11 **int getMaximum(int field) **
      Returns the maximum value of the given calendar field for this GregorianCalendar instance.
      12 Date getTime()
      Gets the current time of the calendar.
      13 **long getTimeInMillis() **
      Gets the current time of the calendar as a long integer
      14 **TimeZone getTimeZone() **
      Gets the time zone.
      15 **int getMinimum(int field) **
      Returns the minimum value of the given field.
      16 **int hashCode() **
      Overrides hashCode.
      17 boolean isLeapYear(int year)
      Determines whether the given year is a leap year.
      18 **void roll(int field, boolean up) **
      Adds or subtracts (up/down) a single time unit on the given time field without changing larger fields.
      19 **void set(int field, int value) **
      Sets the time field with the given value.
      20 **void set(int year, int month, int date) **
      Sets the values of year, month, and day.
      21 **void set(int year, int month, int date, int hour, int minute) **
      Sets the values of year, month, day, hour, and minute.
      22 **void set(int year, int month, int date, int hour, int minute, int second) **
      Sets the values of year, month, day, hour, minute, and second.
      23 **void setGregorianChange(Date date) **
      Sets the GregorianCalendar change date.
      24 **void setTime(Date date) **
      Sets the current time of the Calendar with the given date.
      25 **void setTimeInMillis(long millis) **
      Sets the current time of the Calendar with the given long millisecond value.
      26 **void setTimeZone(TimeZone value) **
      Sets the current time zone with the given time zone value.
      27 **String toString() **
      Returns a string representing the calendar.

      Example

      Example

      import

      java

      .

      util

      .*;

      public

      class

      GregorianCalendarDemo

      {

      public

      static

      void

      main

      (

      String

      [

      ]

      args

      )

      {

      String

      months

      [

      ]

      =

      {

      "

      Jan

      "

      ,

      "

      Feb

      "

      ,

      "

      Mar

      "

      ,

      "

      Apr

      "

      ,

      "

      May

      "

      ,

      "

      Jun

      "

      ,

      "

      Jul

      "

      ,

      "

      Aug

      "

      ,

      "

      Sep

      "

      ,

      "

      Oct

      "

      ,

      "

      Nov

      "

      ,

      "

      Dec

      "

      }

      ;

      int

      year

      ;

      //

      Initialize the Gregorian calendar

      //

      Use the current time and date

      //

      Defaults to local time and time zone

      GregorianCalendar

      gcalendar

      =

      new

      GregorianCalendar

      (

      )

      ;

      //

      Display current time and date information

      System

      .

      out

      .

      print

      (

      "

      Date:

      "

      )

      ;

      System

      .

      out

      .

      print

      (

      months

      [

      gcalendar

      .

      get

      (

      Calendar

      .

      MONTH

      )

      ]

      )

      ;

      System

      .

      out

      .

      print

      (

      "

      "

      gcalendar

      .

      get

      (

      Calendar

      .

      DATE

      )

      "

      "

      )

      ;

      System

      .

      out

      .

      println

      (

      year

      =

      gcalendar

      .

      get

      (

      Calendar

      .

      YEAR

      )

      )

      ;

      System

      .

      out

      .

      print

      (

      "

      Time:

      "

      )

      ;

      System

      .

      out

      .

      print

      (

      gcalendar

      .

      get

      (

      Calendar

      .

      HOUR

      )

      "

      :

      "

      )

      ;

      System

      .

      out

      .

      print

      (

      gcalendar

      .

      get

      (

      Calendar

      .

      MINUTE

      )

      "

      :

      "

      )

      ;

      System

      .

      out

      .

      println

      (

      gcalendar

      .

      get

      (

      Calendar

      .

      SECOND

      )

      )

      ;

      //

      Test whether the current year is a leap year

      if

      (

      gcalendar

      .

      isLeapYear

      (

      year

      )

      )

      {

      System

      .

      out

      .

      println

      (

      "

      The current year is a leap year

      "

      )

      ;

      }

      else

      {

      System

      .

      out

      .

      println

      (

      "

      The current year is not a leap year

      "

      )

      ;

      }

      }

      }

      Run Example »

      The compilation and execution results of the above example are as follows:

      
      Date: Apr 22 2009
      Time: 11:25:27
      当前年份不是闰年
      

      For the complete list of Calendar class methods, you can refer to the standard Java documentation.