Monday, June 5, 2017

Java 8 Date and Time API: How to Convert Date to Java 8 Date and Time


In this tutorial, you will learn:
  • How to convert Date to Instant
  • How to convert Date to LocalDate
  • How to convert Date to LocalTime
  • How to convert Date to LocalDateTime
  • How to convert Date to ZonedDateTime
Example
package com.melody.datetime;

import java.time.Instant;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.util.Date;

public class ConvertDateToJava8Date {

 public static void main(String[] args) {
  // Date has no timezone
  Date date = new Date();

  // I did not use toString() because it will automatically
  // format the date with the system default timezone
  System.out.println("Date: " + date.toGMTString());

  // Convert Date to Instant.
  // Instant is the equivalent of Date in Java 8 Date API.
  Instant instant = date.toInstant();
  System.out.println("Instant: " + instant);

  ZoneId defaultTimeZone = ZoneId.systemDefault();

  // Convert Instant to LocalDate (using the system default timezone)
  LocalDate localDate = instant.atZone(defaultTimeZone).toLocalDate();
  System.out.println("LocalDate: " + localDate);

  // Convert Instant to LocalTime (using the system default timezone)
  LocalTime localTime = instant.atZone(defaultTimeZone).toLocalTime();
  System.out.println("LocalTime: " + localTime);

  // Convert Instant to LocalDateTime (using the system default timezone)
  LocalDateTime localDateTime = instant.atZone(defaultTimeZone).toLocalDateTime();
  System.out.println("LocalDateTime: " + localDateTime);

  // Convert Instant to ZonedDateTime (using the system default timezone)
  ZonedDateTime zonedDateTime = instant.atZone(defaultTimeZone);
  System.out.println("ZonedDateTime: " + zonedDateTime);
 }
}
Output

Date: 5 Jun 2017 09:01:52 GMT
Instant: 2017-06-05T09:01:52.527Z
LocalDate: 2017-06-05
LocalTime: 17:01:52.527
LocalDateTime: 2017-06-05T17:01:52.527
ZonedDateTime: 2017-06-05T17:01:52.527+08:00[Asia/Shanghai]


Java 8 Date and Time API: How to Compare Date and Time


In this tutorial, you will learn:
  • How to compare two given LocalDate (e.g. determine if two LocalDate are equal)
  • How to compare two given LocalTime (e.g. determine if two LocalTime are equal)
  • How to find the difference between two LocalDate(e.g. number of days in between)
  • How to find the difference between two LocalTime (e.g. number of minutes in between)
Example
package com.melody.datetime;

import java.time.LocalDate;
import java.time.LocalTime;
import java.time.temporal.ChronoUnit;

public class CompareDateTimeDemo {

 public static void main(String[] args) {
  // Compare LocalDate and calculate differences between two LocalDate
  LocalDate localDate1 = LocalDate.now();
  LocalDate localDate2 = localDate1.plusDays(30);

  System.out.println("Date 1: " + localDate1);
  System.out.println("Date 2: " + localDate2);
  System.out.println("Date 1 is after Date 2? " + localDate1.isAfter(localDate2));
  System.out.println("Date 1 is before Date 2? " + localDate1.isBefore(localDate2));
  System.out.println("Date 1 is equal to Date 2? " + localDate1.isEqual(localDate2));
  System.out.println("No. of days between Date 1 and Date 2: " + ChronoUnit.DAYS.between(localDate1, localDate2));

  // Compare LocalTime calculate differences between two LocalTime
  LocalTime localTime1 = LocalTime.now();
  LocalTime localTime2 = localTime1.minusHours(3);

  System.out.println("\nTime 1: " + localTime1);
  System.out.println("Time 2: " + localTime2);
  System.out.println("Time 1 is after Time 2? " + localTime1.isAfter(localTime2));
  System.out.println("Time 1 is before Time 2? " + localTime1.isBefore(localTime2));
  System.out.println("No. of hours between Time 1 and Time 2: " + ChronoUnit.HOURS.between(localTime2, localTime1));
 }
}
Output

Date 1: 2017-06-05
Date 2: 2017-07-05
Date 1 is after Date 2? false
Date 1 is before Date 2? true
Date 1 is equal to Date 2? false
No. of days between Date 1 and Date 2: 30

Time 1: 16:53:59.403
Time 2: 13:53:59.403
Time 1 is after Time 2? true
Time 1 is before Time 2? false
No. of hours between Time 1 and Time 2: 3


Java 8 Date and Time API: How to Convert a Time Zone between Countries


In this tutorial, you will learn:
  • How to convert a time zone between different countries using the new Java 8 Date and Time API
Example
package com.melody.datetime;

import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;

public class ConvertTimezoneDemo {

 public static void main(String[] args) {
  DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MM/dd/yyyy hh:mm:ss a");

  String dateAsString = "05/13/2017 07:30:45 AM";

  // Instantiate a LocalDateTime (without timezone)
  LocalDateTime localDateTime = LocalDateTime.parse(dateAsString, formatter);
  System.out.println("Local date & time without timezone: " + localDateTime.format(formatter));

  // Convert LocalDateTime to ZonedDateTime (timezone = Shanghai)
  ZoneId shanghaiZoneId = ZoneId.of("Asia/Shanghai");
  ZonedDateTime shanghaiZonedDateTime = localDateTime.atZone(shanghaiZoneId);
  System.out.println("Date & time in Shanghai: " + shanghaiZonedDateTime.format(formatter)
     + " " + shanghaiZonedDateTime.getZone());

  // Convert ZonedDateTime to another timezone
  ZoneId newYorkZoneId = ZoneId.of("America/New_York");
  ZonedDateTime newYorkZonedDateTime = shanghaiZonedDateTime.withZoneSameInstant(newYorkZoneId);
  System.out.println("Date & time in New York: " + newYorkZonedDateTime.format(formatter)
    + " " + newYorkZonedDateTime.getZone());
 }
}
Output

Local date & time without timezone: 05/13/2017 07:30:45 AM
Date & time in Shanghai: 05/13/2017 07:30:45 AM Asia/Shanghai
Date & time in New York: 05/12/2017 07:30:45 PM America/New_York


Wednesday, May 17, 2017

Java 8 Date and Time API: DateTimeFormatter


In this tutorial, you will learn:

  • How to format LocalDateTime (date to text)
  • How to parse (convert) String to LocalDateTime (text to date)
Example
package com.melody.datetime;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

public class DateTimeFormatterDemo {

 public static void main(String[] args) {
  DateTimeFormatter formatter1 = DateTimeFormatter.ofPattern("MM-dd-yyyy hh:mm:ss a");
  DateTimeFormatter formatter2 = DateTimeFormatter.ofPattern("MM/dd/yyyy HH:mm:ss");

  // Format LocalDateTime (date to text)
  LocalDateTime currentDateTime = LocalDateTime.now();
  System.out.println("Default date & time format: " + currentDateTime);


  String formattedDateTime = currentDateTime.format(formatter1);
  System.out.println("Format LocalDateTime (date to text): " + formattedDateTime);

  // Parse (convert) String to LocalDateTime (text to date)
  String dateAsString = "05/13/2017 14:30:45";
  System.out.println("Date string to parse: " + dateAsString);

  LocalDateTime parsedDateTime = LocalDateTime.parse(dateAsString, formatter2);
  System.out.println("Parse string to LocalDateTime (text to date): " + parsedDateTime);
 }
}
Output

Default date & time format: 2017-05-17T20:41:33.205
Format LocalDateTime (date to text): 05-17-2017 08:41:33 PM
Date string to parse: 05/13/2017 14:30:45
Parse string to LocalDateTime (text to date): 2017-05-13T14:30:45



Java 8 Date and Time API: ZonedDateTime


Java 8 date and time API introduces a new class ZonedDateTime under java.time package which represents a local date and time with a timezone. ZonedDateTime instances are immutable (cannot be changed) so any operations performed on ZonedDateTime will always return a new instance.

In this tutorial, you will learn:
  • How to create a ZonedDateTime instance representing the current date and time with a timezone
  • How to create a ZonedDateTime instance from a given LocalDate,  LocalTime and timezone
  • How to access the ZonedDateTime properties (e.g. month, year, day of week, etc.)
  • How to perform plus and minus operations on ZonedDateTime
  • How to create instance of ZoneId using offset and timezone location
Example
package com.melody.datetime;

import java.time.LocalDate;
import java.time.LocalTime;
import java.time.Period;
import java.time.ZoneId;
import java.time.ZonedDateTime;

public class ZonedDateTimeDemo {

 public static void main(String[] args) {
  ZonedDateTime currentZonedDateTime = ZonedDateTime.now();
  System.out.println("Current date and time with timezone: "
    + currentZonedDateTime);

  // Create a ZonedDateTime instance from a given date,
  // time and timezone
  ZoneId zoneId = ZoneId.systemDefault();
  LocalDate localDate = LocalDate.of(2017, 11, 14);
  LocalTime localTime = LocalTime.of(13, 30, 44);
  ZonedDateTime zonedDateTime = ZonedDateTime.of(localDate, localTime, zoneId);
  System.out.println("ZonedDateTime instance from date and time using system timezone: "
    + zonedDateTime);

  // Access the ZonedDateTime properties
  System.out.println("Get date: " + zonedDateTime.toLocalDate());
  System.out.println("Get time: " + zonedDateTime.toLocalTime());
  System.out.println("Get timezone: " + zonedDateTime.getZone());
  System.out.println("Get year: " + zonedDateTime.getYear());
  System.out.println("Get month (enum): " + zonedDateTime.getMonth());
  System.out.println("Get month: " + zonedDateTime.getMonthValue());
  System.out.println("Get day of month: " + zonedDateTime.getDayOfMonth());
  System.out.println("Get hour: " + zonedDateTime.getHour());
  System.out.println("Get minute: " + zonedDateTime.getMinute());
  System.out.println("Get second: " + zonedDateTime.getSecond());

  // Add and minus operations on ZonedDateTime
  // using Period instead of plusXX or minusXX because it can
  // give more accurate calculation when daylight saving changes
  // are involved.
  System.out.println("Add 1 yr to 2017-11-14: " + zonedDateTime.plus(Period.ofYears(1)));
  System.out.println("Minus 1 yr, 1 month & 1 day from 2017-11-14: " + zonedDateTime.minus(Period.of(1, 1, 1)));

  // Create instance of ZoneId using offset
  ZoneId zoneId1 = ZoneId.of("UTC+8");
  System.out.println("Zone Id using offset UTC+8: " + zoneId1);

  // Create instance of ZoneId using timezone location (continent/city)
  ZoneId zoneId2 = ZoneId.of("Asia/Shanghai");
  System.out.println("Zone Id using timezone location Asia/Shanghai: " + zoneId2);
 }
}

Output

Current date and time with timezone: 2017-05-17T20:34:02.561+08:00[Asia/Shanghai]
ZonedDateTime instance from date and time using system timezone: 2017-11-14T13:30:44+08:00[Asia/Shanghai]
Get date: 2017-11-14
Get time: 13:30:44
Get timezone: Asia/Shanghai
Get year: 2017
Get month (enum): NOVEMBER
Get month: 11
Get day of month: 14
Get hour: 13
Get minute: 30
Get second: 44
Add 1 yr to 2017-11-14: 2018-11-14T13:30:44+08:00[Asia/Shanghai]
Minus 1 yr, 1 month & 1 day from 2017-11-14: 2016-10-13T13:30:44+08:00[Asia/Shanghai]
Zone Id using offset UTC+8: UTC+08:00
Zone Id using timezone location Asia/Shanghai: Asia/Shanghai