64. Getting date and time units

For a Date object, the solution may rely on a Calendar instance. The code that is bundled to this book contains this solution.

For JDK 8 classes, Java provides dedicated getFoo() methods and a  get​(TemporalField field) method. For example, let's assume the following LocalDateTime object:

LocalDateTime ldt = LocalDateTime.now();

Relying on getFoo() methods, we get the following code:

int year = ldt.getYear();
int month = ldt.getMonthValue();
int day = ldt.getDayOfMonth();
int hour = ldt.getHour();
int minute = ldt.getMinute();
int second = ldt.getSecond();
int nano = ldt.getNano();

Or, relying on get​(TemporalField field) results in the following:

int yearLDT = ldt.get(ChronoField.YEAR);
int monthLDT = ldt.get(ChronoField.MONTH_OF_YEAR);
int dayLDT = ldt.get(ChronoField.DAY_OF_MONTH);
int hourLDT = ldt.get(ChronoField.HOUR_OF_DAY);
int minuteLDT = ldt.get(ChronoField.MINUTE_OF_HOUR);
int secondLDT = ldt.get(ChronoField.SECOND_OF_MINUTE);
int nanoLDT = ldt.get(ChronoField.NANO_OF_SECOND);

Notice that the months are counted from one, which is January.

For example, a LocalDateTime object of 2019-02-25T12:58:13.109389100 can be cut into date-time units, resulting in the following:

Year: 2019 Month: 2 Day: 25 Hour: 12 Minute: 58 Second: 13 Nano: 109389100

With a little intuition and documentation, it is very easy to adapt this example for LocalDate, LocalTime, ZonedDateTime, and others.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.144.19.243