Java 8 DateTime API Example




Hey guys in this article, you will learn about Java 8 DateTime API with example

Read More:

package in.bushansirgur.datetime;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.Month;

public class DateTimeChecker {
	public static void main(String args[]) {
        DateTimeChecker dateTimeChecker = new DateTimeChecker();
        dateTimeChecker.DateTime();
    }

    public void DateTime() {
        // Get the current date and time
        LocalDateTime currentTime = LocalDateTime.now();
        System.out.println("Current DateTime: " + currentTime);

        LocalDate date1 = currentTime.toLocalDate();
        System.out.println("Date : " + date1);

        Month month = currentTime.getMonth();
        int day = currentTime.getDayOfMonth();
        int seconds = currentTime.getSecond();

        System.out.println("Month : " + month);
        System.out.println("Day : " + day);
        System.out.println("Seconds : " + seconds);

        LocalDateTime date2 = currentTime.withDayOfMonth(17).withYear(2018);
        System.out.println("Date : " + date2);

        //Prints 17 May 2018
        LocalDate date3 = LocalDate.of(2018, Month.MAY, 17);
        System.out.println("Date : " + date3);

        //Prints 04 hour 45 minutes
        LocalTime date4 = LocalTime.of(4, 45);
        System.out.println("Date : " + date4);

        // Convert to a String 
        LocalTime date5 = LocalTime.parse("20:15:30");
        System.out.println("Date : " + date5);
    }
}

Output:

Date : 2022-01-03
Month : JANUARY
Day : 3
Seconds : 13
Date : 2018-01-17T19:21:13.640670800
Date : 2018-05-17
Date : 04:45
Date : 20:15:30

That’s it for this post, if you like this post, share this with your friends and colleagues or you can share this within your social media platform. Thanks, I will see you in our next post.



Bushan Sirgur

Hey guys, I am Bushan Sirgur from Banglore, India. Currently, I am working as an Associate project in an IT company.

Leave a Reply