Dealing with Date, Time & Time Zones in JAVA

Photo by Aron Visuals on Unsplash

What is Time Zones?

What is UTC?

What is Daylight Saving Time?

Therefore, How to deal with Time and Date?

Before JDK8

JAVA 8 Time & Date API

LocalDate

LocalDate today = LocalDate.now(); // gives the current date on
//local machine
LocalDate Christmas = LocalDate.of(2021,12,25);
or
LocalDate Christmas = LocalDate.parse("2020-12-25");//parsing as a
//String
LocalDate today = LocalDate.now();
LocalDate tomorrow = today.plusDays(1); // Add given days
LocalDate yesterday = today.minusDays(1); // subtract given days

LocalTime

LocalTime now  = LocalTime.now();
LocalTime sunrise = LocalTime.of(5,25,23); //hh:mm:ss
LocalTime sunset = LocalTime.parse("18:05:30"); //parsing as a
//string

LocalDateTime

LocalDateTime now = LocalDateTime.now();or
LocalDate today = LocalDate.now();
LocalTime current = LocalTime.now();
LocalDateTime now = LocalDateTime.of(today, current);
or
LocalDateTime now = LocalDateTime.parse("2007-12-03T10:15:30");

ZonedDateTime

ZonedDateTime now = ZonedDateTime.now();or
LocalDateTime t1 = LocalDateTime.parse("2007-12-03T10:15:30");
ZoneId srilanka = ZoneId.of("Asia/Colombo");
ZonedDateTime t2 = ZonedDateTime.of(t1,srilanka);
or
ZonedDateTime now = ZonedDateTime.now("2007-12-03T10:15:30+01:00[Europe/Paris]");

Time conversion

ZoneId moscow= ZoneId.of("Europe/Moscow");
ZoneId newyork = ZoneId.of("America/New_York");
ZonedDateTime SL_Time = ZonedDateTime.now();// local machine is in
//Sri Lanka

ZonedDateTime New_York = SL_Time.withZoneSameInstant(newyork); //Represent new yok time
ZonedDateTime Russia = SL_Time.withZoneSameInstant(moscow); //Represent Russia time (Moscow)

NOTE

Keep Learning ❤️

Associate Software Engineer at Virtusa