Java Date Time
# Java Date and Time \n\nJava provides multiple sets of date and time APIs. Below is a comparison of the main categories and a summary of common methods:\n\n| Category | Main Classes | Thread-Safe | Mutability | Java Version | Features |\n| --- | --- | --- | --- | --- | --- |\n| Legacy Date | (#), (#), (#) | No | Mutable | 1.0+ | Many design flaws, not recommended for use |\n| New Date/Time | (#), (#), (#), (#), (#) | Yes | Immutable | 8+ | Well-designed, recommended for use |\n| Timestamp | (#) | Yes | Immutable | 8+ | Machine time, precise to nanoseconds |\n| Formatting | (#) | Yes | Immutable | 8+ | Thread-safe formatting class |\n\n* * *\n\n## LocalDate/DateTimeFormatter\n\nLocalDate/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.\n\n## Example\n\n```java\nimport java.time.LocalDate;\nimport java.time.format.DateTimeFormatter;\n\npublic class TutorialTest {\n public static void main(String[] args){\n // Get current date\n LocalDate today = LocalDate.now();\n System.out.println("Current date: " + today);\n\n // Create specific date\n LocalDate nationalDay = LocalDate.of(2025, 10, 1);\n System.out.println("National Day: " + nationalDay);\n\n // Date addition and subtraction\n LocalDate tomorrow = today.plusDays(1);\n LocalDate nextMonth = today.plusMonths(1);\n LocalDate lastYear = today.minusYears(1);\n\n System.out.println("Tomorrow: " + tomorrow);\n System.out.println("Next month: " + nextMonth);\n System.out.println("This day last year: " + lastYear);\n }\n}\n\nThe output of the above example is:\n\nCurrent date: 2025-05-01\nNational Day: 2025-10-01\nTomorrow: 2025-05-02\nNext month: 2025-06-01\nThis day last year: 2024-05-01\n\n1. **Prioritize using the `java.time` package for new projects** (Java 8+)\n\n2. **Avoid using the legacy `Date` and `Calendar` classes**\n\n3. **Clearly distinguish time zone usage**:\n * No time zone needed: `LocalDate`/`LocalTime`/`LocalDateTime`\n * Time zone needed: `ZonedDateTime`\n\n4. **Consider thread safety when formatting**: Use `DateTimeFormatter` instead of `SimpleDateFormat`\n\n5. **Database interaction**:\n * JDBC 4.2+ directly supports `java.time` types\n * Older versions can be converted to `java.sql.Date`/`Timestamp`\n\n**1. LocalDate (Date)**\n\n## Example\n\n```java\nLocalDate today = LocalDate.now();\nLocalDate date = LocalDate.of(2023, Month.JUNE, 15);\n\nint year = date.getYear(); // 2023\nMonth month = date.getMonth(); // JUNE\nint day = date.getDayOfMonth(); // 15\n\nLocalDate nextWeek = today.plusWeeks(1);\nboolean isLeap = date.isLeapYear(); // Is it a leap year?\n\n**2. LocalTime (Time)**\n\n## Example\n\n```java\nLocalTime now = LocalTime.now();\nLocalTime time = LocalTime.of(14, 30, 45); // 14:30:45\n\nint hour = time.getHour(); // 14\nint minute = time.getMinute(); // 30\n\nLocalTime nextHour = time.plusHours(1);\n\n**3. LocalDateTime (Date and Time)**\n\n## Example\n\n```java\nLocalDateTime ldt = LocalDateTime.now();\nLocalDateTime dt = LocalDateTime.of(2023, 6, 15, 14, 30);\nLocalDateTime nextMonth = dt.plusMonths(1);\n\n**4. ZonedDateTime (Date and Time with Time Zone)**\n\n## Example\n\n```java\nZonedDateTime zdt = ZonedDateTime.now(ZoneId.of("Asia/Shanghai"));\nZonedDateTime nyTime = zdt.withZoneSameInstant(ZoneId.of("America/New_York"));\nZoneId zone = zdt.getZone(); // Get time zone\n\n**5. Instant (Timestamp)**\n\n## Example\n\n```java\nInstant now = Instant.now(); // Get current timestamp\nInstant later = now.plusSeconds(60); // 60 seconds later\nlong epochMilli = now.toEpochMilli(); // Get millisecond timestamp\n\n* * *\n\n## Date Class\n\nThe `java.util` package provides the `Date` class to encapsulate the current date and time. The `Date` class provides two constructors to instantiate `Date` objects.\n\nThe first constructor initializes the object with the current date and time.\n\n`Date()`\n\nThe second constructor takes a parameter, which is the number of milliseconds since January 1, 1970.\n\n`Date(long millisec)`\n\nAfter a `Date` object is created, the following methods can be called.\n\n| No. | Method and Description |\n| --- | --- |\n| 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. |\n| 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. |\n| 3 | **Object clone( )** Returns a copy of this object. |\n| 4 | **int compareTo(Date date)** Compares the Date object on which this method is called with the specified date. Returns 0 if they are equal. Returns a negative number if the calling object is before the specified date. Returns a positive number if the calling object is after the specified date. |\n| 5 | **int compareTo(Object obj)** If `obj` is of type `Date`, the operation is equivalent to `compareTo(Date)`. Otherwise, it throws a `ClassCastException`. |\n| 6 | **boolean equals(Object date)** Returns true if the Date object on which this method is called is equal to the specified date, otherwise returns false. |\n| 7 | **long getTime( )** Returns the number of milliseconds since January 1, 1970, 00:00:00 GMT represented by this Date object. |\n| 8 | **int hashCode( )** Returns the hash code value of this object. |\n| 9 | **void setTime(long time)** Sets the date and time using the number of milliseconds after January 1, 1970, 00:00:00 GMT. |\n| 10 | **String toString( )** Converts this Date object to a String of the form: dow mon dd hh:mm:ss zzz yyyy, where: dow is the day of the week (Sun, Mon, Tue, Wed, Thu, Fri, Sat). |\n\n* * *\n\n## Getting Current Date and Time\n\nGetting the current date and time in Java is simple. Use the `toString()` method of the `Date` object to print the current date and time, as shown below:\n\n## Example\n\n```java\nimport java.util.Date;\n\npublic class DateDemo {\n public static void main(String[] args) {\n Date date = new Date();\n System.out.println(date.toString());\n }\n}\n\n[Run Example Β»](#)\n\nThe compilation and execution result of the above example is:\n\nMon May 04 09:51:52 CDT 2013\n\n* * *\n\n## Date Comparison\n\nJava uses the following three methods to compare two dates:\n\n* Use the `getTime()` method to get the two dates (the number of milliseconds since January 1, 1970), and then compare these two values.\n* Use the methods `before()`, `after()`, and `equals()`. For example, the 12th of a month is earlier than the 18th, so `new Date(99, 2, 12).before(new Date(99, 2, 18))` returns `true`.\n* Use the `compareTo()` method, which is defined by the `Comparable` interface. The `Date` class implements this interface.\n\n### 1. Using the `getTime()` Method for Comparison\n\nThis method compares the number of milliseconds since January 1, 1970 (Unix epoch) of the date objects.\n\n## Example\n\n```java\nimport java.util.Date;\n\npublic class DateComparison {\n public static void main(String[] args) {\n Date date1 = new Date(121, 5, 15); // June 15, 2021\n Date date2 = new Date(121, 5, 20); // June 20, 2021\n\n // Compare milliseconds\n if (date1.getTime() date2.getTime()) {\n System.out.println("date1 is after date2");\n } else {\n System.out.println("The two dates are the same");\n }\n }\n}\n\nOutput:\n\ndate1 is before date2\n\n### 2. Using the `before()`, `after()`, and `equals()` Methods\n\nThese are built-in comparison methods of the `Date` class with clearer semantics.\n\n## Example\n\n```java\nimport java.util.Date;\n\npublic class DateComparison {\n public static void main(String[] args) {\n Date date1 = new Date(121, 5, 15); // June 15, 2021\n Date date2 = new Date(121, 5, 20); // June 20, 2021\n\n // Using before() method\n System.out.println("Is date1 before date2? " + date1.before(date2));\n\n // Using after() method\n System.out.println("Is date1 after date2? " + date1.after(date2));\n\n // Using equals() method\n System.out.println("Are the two dates the same? " + date1.equals(date2));\n }\n}\n\nOutput:\n\nIs date1 before date2? true\nIs date1 after date2? false\nAre the two dates the same? false\n\n### 3. Using the `compareTo()` Method\n\nThe `Date` class implements the `Comparable` interface, so the `compareTo()` method can be used for comparison.\n\n## Example\n\n```java\nimport java.util.Date;\n\npublic class DateComparison {\n public static void main(String[] args) {\n Date date1 = new Date(121, 5, 15); // June 15, 2021\n Date date2 = new Date(121, 5, 20); // June 20, 2021\n\n int result = date1.compareTo(date2);\n\n if (result 0) {\n System.out.println("date1 is after date2");\n } else {\n System.out.println("The two dates are the same");\n }\n }\n}\n\nOutput:\n\ndate1 is before date2\n\n* * *\n\n## Formatting Dates Using SimpleDateFormat\n\n`SimpleDateFormat` is a class for formatting and analyzing dates in a locale-sensitive manner. `SimpleDateFormat` allows you to choose any user-defined date-time format to run. For example:\n\n## Example\n\n```java\nimport java.util.*;\nimport java.text.*;\n\npublic class DateDemo {\n public static void main(String[] args) {\n Date dNow = new Date();\n SimpleDateFormat ft = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");\n System.out.println("Current time: " + ft.format(dNow));\n }\n}\n\n[Run Example Β»](#)\n\n```java\nSimpleDateFormat ft = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");\n\nThis line of code establishes the conversion format, where `yyyy` is the full year, `MM` is the month, `dd` is the day, and `HH:mm:ss` is the hour, minute, and second.\n\n**Note**: Some formats are uppercase, and some are lowercase. For example, `MM` is the month, `mm` is the minute; `HH` is the 24-hour clock, while `hh` is the 12-hour clock.\n\nThe compilation and execution result of the above example is:\n\nCurrent time: 2018-09-06 10:16:34\n\n* * *\n\n## Date and Time Formatting Codes\n\nThe time pattern string is used to specify the time format. In this pattern, all ASCII letters are reserved as pattern letters, defined as follows:\n\n| **Letter** | **Description** | **Example** |\n| --- | --- | --- |\n| G | Era marker | AD |\n| y | Four-digit year | 2001 |\n| M | Month | July or 07 |\n| d | Day of the month | 10 |\n| h | A.M./P.M. (1~12) hour | 12 |\n| H | Hour of the day (0~23) | 22 |\n| m | Minute | 30 |\n| s | Second | 55 |\n| S | Millisecond | 234 |\n| E | Day of the week | Tuesday |\n| D | Day of the year | 360 |\n| F | Day of the week in the month | 2 (second Wed. in July) |\n| w | Week number of the year | 40 |\n| W | Week number of the month | 1 |\n| a | A.M./P.M. marker | PM |\n| k | Hour of the day (1~24) | 24 |\n| K | A.M./P.M. (0~11) hour | 10 |\n| z | Time zone | Eastern Standard Time |\n| ' | Text delimiter | Delimiter |\n| " | Single quote | ` |\n\n* * *\n\n## Formatting Dates Using printf\n\nThe `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.\n\n* `%tY`: Outputs a four-digit year, e.g., 2023\n* `%ty`: Outputs a two-digit year, e.g., 23\n* `%tm`: Outputs a two-digit month, e.g., 02\n* `%tB`: Outputs the full name of the month, e.g., February\n* `%tb`: Outputs the abbreviated name of the month, e.g., Feb\n* `%tA`: Outputs the full name of the day of the week, e.g., Wednesday\n* `%ta`: Outputs the abbreviated name of the day of the week, e.g., Wed\n* `%td`: Outputs a two-digit day, e.g., 24\n* `%te`: Outputs a one- or two-digit day, e.g., 24 or 02\n* `%tH`: Outputs the hour in 24-hour format, e.g., 23\n* `%tI`: Outputs the hour in 12-hour format, e.g., 11\n* `%tM`: Outputs the minute, e.g., 45\n* `%tS`: Outputs the second, e.g., 30\n* `%tp`: Outputs A.M. or P.M., e.g., AM or PM\n* `%tZ`: Outputs the time zone, e.g., GMT+08:00\n\n| Conversion | Description | Example |\n| --- | --- | --- |\n| %tc | Includes all date and time information | Saturday, October 27, 14:21:20 CST 2007 |\n| %tF | "Year-Month-Day" format | 2007-10-27 |\n| %tD | "Month/Day/Year" format | 10/27/07 |\n| %tr | "HH:MM:SS PM" format (12-hour clock) | 02:25:51 PM |\n| %tT | "HH:MM:SS" format (24-hour clock) | 14:28:16 |\n| %tR | "HH:MM" format (24-hour clock) | 14:28 |\n\nFor more **printf** parsing, see: (#)\n\n### Example\n\n## Example\n\n```java\nimport java.util.Date;\n\npublic class DateFormatExample {\n public static void main(String[] args) {\n Date date = new Date();\n System.out.printf("%tY-%tm-%td %tH:%tM:%tS %tZ", date, date, date, date, date, date, date);\n }\n}\n\nThe execution output is:\n\n2023-02-24 13:34:45 GMT+08:00\n\n## Example\n\n```java\nimport java.util.Date;\n\npublic class DateDemo {\n public static void main(String[] args) {\n Date date = new Date();\n System.out.printf("All date and time information: %tc%n", date);\n System.out.printf("Year-Month-Day format: %tF%n", date);\n System.out.printf("Month/Day/Year format: %tD%n", date);\n System.out.printf("HH:MM:SS PM format (12-hour clock): %tr%n", date);\n System.out.printf("HH:MM:SS format (24-hour clock): %tT%n", date);\n System.out.printf("HH:MM format (24-hour clock): %tR", date);\n }\n}\n\nThe compilation and execution result of the above example is:\n\nAll date and time information: Monday, September 10, 10:43:36 CST 2012\nYear-Month-Day format: 2012-09-10\nMonth/Day/Year format: 09/10/12\nHH:MM:SS PM format (12-hour clock): 10:43:36 AM\nHH:MM:SS format (24-hour clock): 10:43:36\nHH:MM format (24-hour clock): 10:43\n\nIf you need to provide the date repeatedly, formatting each part in this way can be a bit complex. Therefore, you can use a format string to indicate the index of the argument to be formatted.\n\nThe index must immediately follow the `%` and must end with `$`. For example:\n\n## Example\n\n```java\nimport java.util.Date;\n\npublic class DateDemo {\n public static void main(String[] args) {\n Date date = new Date();\n System.out.printf("%1$s %2$tB %2$td, %2$tY", "Due date:", date);\n }\n}\n\n[Run Example Β»](#)\n\nThe compilation and execution result of the above example is:\n\nDue date: February 09, 2014\n\nAlternatively, you can use the `<` flag. It indicates that the previously formatted argument should be used again. For example:\n\n## Example\n\n```java\nimport java.util.Date;\n\npublic class DateDemo {\n public static void main(String[] args) {\n Date date = new Date();\n System.out.printf("%s %tB %<te, %<tY", "Due date:", date);\n }\n}\n\n[Run Example Β»](#)\n\nThe compilation and execution result of the above example is:\n\nDue date: February 09, 2014\n\nDefining date format conversion characters allows dates to generate new strings through specified conversion characters. These date conversion characters are shown below:\n\n## Example\n\n```java\nimport java.util.*;\n\npublic class DateDemo {\n public static void main(String[] args) {\n Date date = new Date();\n String str = String.format(Locale.US, "English month abbreviation: %tb", date);\n System.out.println(str);\n System.out.printf("Local month abbreviation: %tb%n", date);\n str = String.format(Locale.US, "English month full name: %tB", date);\n System.out.println(str);\n System.out.printf("Local month full name: %tB%n", date);\n str = String.format(Locale.US, "English day of week abbreviation: %ta", date);\n System.out.println(str);\n System.out.printf("Local day of week abbreviation: %tA%n", date);\n System.out.printf("First two digits of year (pad with 0 if less than two): %tC%n", date);\n System.out.printf("Last two digits of year (pad with 0 if less than two): %ty%n", date);\n System.out.printf("Day of the year (i.e., the nth day of the year): %tj%n", date);\n System.out.printf("Two-digit month (pad with 0 if less than two): %tm%n", date);\n System.out.printf("Two-digit day (pad with 0 if less than two): %td%n", date);\n System.out.printf("Day of the month (no padding): %te", date);\n }\n}\n\nOutput:\n\nEnglish month abbreviation: May\nLocal month abbreviation: May\nEnglish month full name: May\nLocal month full name: May\nEnglish day of week abbreviation: Thu\nLocal day of week abbreviation: Thursday\nFirst two digits of year (pad with 0 if less than two): 20\nLast two digits of year (pad with 0 if less than two): 17\nDay of the year (i.e., the nth day of the year): 124\nTwo-digit month (pad with 0 if less than two): 05\nTwo-digit day (pad with 0 if less than two): 04\nDay of the month (no padding): 4\n\n* * *\n\n## Parsing Strings to Time\n\nThe `SimpleDateFormat` class has some additional methods, especially `parse()`, which attempts to parse a string according to the format stored in the given `SimpleDateFormat` object. For example:\n\n## Example\n\n```java\nimport java.util.*;\nimport java.text.*;\n\npublic class DateDemo {\n public static void main(String[] args) {\n SimpleDateFormat ft = new SimpleDateFormat("yyyy-MM-dd");\n String input = args.length == 0 ? "1818-11-11" : args;\n System.out.print(input + " Parses as ");\n Date t;\n try {\n t = ft.parse(input);\n System.out.println(t);\n } catch (ParseException e) {\n System.out.println("Unparseable using " + ft);\n }\n }\n}\n\n[Run Example Β»](#)\n\nThe compilation and execution result of the above example is:\n\n$ java DateDemo\n1818-11-11 Parses as Wed Nov 11 00:00:00 1818
YouTip