Java ZonedDateTime
New Date
From Java 8, there are additional Date management class.
In the past, Date related class for Java are following
- Date
- Calendar
From Java 8, several classes are added, these are some of them.
- ZonedDateTime
- LocalDateTime
- LocalDate
- LocalTime
What is difference between Zonedxxx and Localxxxx.
Zonedxxx has Zone data, date can change using ZoneId.
Localxxx is only local date. It doesn’t have Zone idea and other timezone date.
I introduce the usage of this. This entry is first for them.
ZonedDateTime
ZonedDateTime has timezone idea.
By default, timezone is system.
System Zone and Zone set
UTC
ZonedDateTime utc = ZonedDateTime.now(ZoneOffset.UTC); System.out.println(utc); zoneId zoneIdUTC = ZoneId.of("UTC"); ZoneId zoneId = ZoneId.of("Asia/Tokyo"); ZonedDateTime jst = ZonedDateTime.ofInstant(utc.toInstant() , zoneId ); // Convert JST
Style
ZonedDateTime gmt = ZonedDateTime.parse("2016-07-06T09:30:40Z[GMT]"); ZonedDateTime sing = ZonedDateTime.parse("2016-07-04T12:30:40+01:00[GMT+08:00]"); System.out.println(gmt); // 2016-07-06T09:30:40Z[GMT] System.out.println(sing); // 2016-07-04T12:30:40+08:00[GMT+08:00]
Convert other class
// Date ZonedDateTime utc = ZonedDateTime.now(ZoneOffset.UTC); Date date = Date.from(utc.toInstant()); System.out.println(date); ZonedDateTime today = ZonedDateTime.now(); System.out.println("ZonedDateTime " + today); System.out.println("LocalDate " + today.toLocalDate()); System.out.println("LocalDateTime " + today.toLocalDateTime()); System.out.println("LocalTime " + today.toLocalTime());
Get Data and Calculation
ZonedDateTime today = ZonedDateTime.now(); System.out.println("Year:" + today.getDayOfYear()); System.out.println("Month:" + today.getMonth()); System.out.println("Day:" + today.getDayOfMonth()); ZonedDateTime firstDayofMonth = today.withDayOfMonth(1); System.out.println(firstDayofMonth);
Calculation
This sample is to calculate flight time.
// Start from Singapore(Changi) 2016/07/07 10:00 am ZonedDateTime start = ZonedDateTime.of(2016, 7, 7, 10, 0, 0, 0, ZoneId.of("Asia/Singapore")); // Flight is 6 hour 30 minutes to Japan(Haneda) ZonedDateTime arrive = start.plusHours(6).plusMinutes(30).withZoneSameInstant(ZoneId.of("Asia/Tokyo")); System.out.println(arrive);
Next entry, I want to explain about dateformat