Java Reference
In-Depth Information
Which method is the correct way? Most of the time, all methods will execute the same logic. However,
some methods are more readable than others. In this case, the code calling the
toLocalTime()
method of the
ZonedDateTime
class should be used as it is straightforward and most readable. At least, you should not extract the
time components from the
ZonedDateTime
to construct the
LocalTime
, as shown in the fifth method in the example.
Non-ISO Calendar Systems
The date classes such as
LocalDate
use the ISO calendar system, which is the Gregorian calendar. The Date-Time API
also lets you use other calendars such as Thai Buddhist calendar, Hijrah calendar, Minguo calendar, and Japanese
calendar. The non-ISO calendar-related classes are in the
java.time.chrono
package.
There is an
XxxChronology
and
XxxDate
class for each of the available non-ISO calendar system. The
XxxChronology
class represents the
Xxx
calendar system whereas
XxxDate
class represents a date in the
Xxx
calendar
system. Each
XxxChronology
class contains an
INSTANCE
constant that represents a singleton instance of that class.
For example,
HijrahChronology
and
HijrahDate
are classes that you will be using to work with the Hijrah calendar
system. The following snippet of code shows two ways to get the current date in the Thai Buddhist calendar:
import java.time.chrono.ThaiBuddhistChronology;
import java.time.chrono.ThaiBuddhistDate;
...
ThaiBuddhistChronology thaiBuddhistChrono = ThaiBuddhistChronology.INSTANCE;
ThaiBuddhistDate now = thaiBuddhistChrono.dateNow();
ThaiBuddhistDate now2 = ThaiBuddhistDate.now();
System.out.println("Current Date in Thai Buddhist: " + now);
System.out.println("Current Date in Thai Buddhist: " + now2);
Current Date in Thai Buddhist: ThaiBuddhist BE 2557-01-09
Current Date in Thai Buddhist: ThaiBuddhist BE 2557-01-09
You can also convert dates in one calendar system to another. ISO dates to non-ISO dates conversion is also
allowed. Converting dates from one calendar system to another is just a matter of calling the
from()
static method of
the target date class and passing the source date object as its parameter. Listing 12-22 shows how to convert ISO date
to Thai Buddhist date and vice versa.
Listing 12-22.
Using the Thai Buddhist and ISO Calendars
// InterCalendarDates.java
package com.jdojo.datetime;
import java.time.LocalDate;
import java.time.chrono.ThaiBuddhistDate;
public class InterCalendarDates {
public static void main(String[] args) {
ThaiBuddhistDate thaiBuddhistNow = ThaiBuddhistDate.now();
LocalDate isoNow = LocalDate.now();
System.out.println("Thai Buddhist Current Date: " + thaiBuddhistNow);
System.out.println("ISO Current Date: " + isoNow);