How to get year, month, day, hours, minutes, seconds and milliseconds of LocalDateTime in Java 8?

Write a Java program that extracts year, month, day, hours, minutes, seconds, and milliseconds of the LocalDateTime in Java 8.
Check out Java 8 examples at Java 8 Examples

Get Year, Month, Day, Hours, Minutes, Seconds and Milliseconds in Java 8

package net.sourcecodeexamples.java;

import java.time.LocalDateTime;
import java.time.temporal.ChronoField;

public class Main {

    public static void main(String[] args) {

        System.out.println("\nStarting with JDK 8:");

        LocalDateTime ldt = LocalDateTime.now();

        int yearLDT = ldt.getYear();
        int monthLDT = ldt.getMonthValue();
        int dayLDT = ldt.getDayOfMonth();
        int hourLDT = ldt.getHour();
        int minuteLDT = ldt.getMinute();
        int secondLDT = ldt.getSecond();
        int nanoLDT = ldt.getNano();

        System.out.println("LocalDateTime: " + ldt);
        System.out.println("Year: " + yearLDT + " Month: " + monthLDT +
            " Day: " + dayLDT + " Hour: " + hourLDT + " Minute: " + minuteLDT +
            " Second: " + secondLDT + " Nano: " + nanoLDT);

        int yearLDT2 = ldt.get(ChronoField.YEAR);
        int monthLDT2 = ldt.get(ChronoField.MONTH_OF_YEAR);
        int dayLDT2 = ldt.get(ChronoField.DAY_OF_MONTH);
        int hourLDT2 = ldt.get(ChronoField.HOUR_OF_DAY);
        int minuteLDT2 = ldt.get(ChronoField.MINUTE_OF_HOUR);
        int secondLDT2 = ldt.get(ChronoField.SECOND_OF_MINUTE);
        int nanoLDT2 = ldt.get(ChronoField.NANO_OF_SECOND);

        System.out.println("Year: " + yearLDT2 + " Month: " + monthLDT2 +
            " Day: " + dayLDT2 + " Hour: " + hourLDT2 + " Minute: " + minuteLDT2 +
            " Second: " + secondLDT2 + " Nano: " + nanoLDT2);
    }
}

Output

Starting with JDK 8:
LocalDateTime: 2020-08-11T14:48:35.227
Year: 2020 Month: 8 Day: 11 Hour: 14 Minute: 48 Second: 35 Nano: 227000000
Year: 2020 Month: 8 Day: 11 Hour: 14 Minute: 48 Second: 35 Nano: 227000000

Related Posts


Comments