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



Java 8 Date and Time API: LocalDateTime


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

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

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.temporal.TemporalAdjusters;

public class LocalDateTimeDemo {

 public static void main(String[] args) {
  LocalDateTime currentLocalDateTime = LocalDateTime.now();
  System.out.println("Current local date and time: " + currentLocalDateTime);

  // Create a LocalDateTime instance from a given year, month,
  // day, hour, minute and second
  LocalDateTime localDateTime = LocalDateTime.of(2017, 11, 14, 13, 45, 30);
  System.out.println("Local date & time from a given year, month, day, hour, minute & second: "
    + localDateTime);

  // Create a LocalDateTime instance from date and time
  LocalDate localDate = LocalDate.of(2017, 11, 14);
  LocalTime localTime = LocalTime.of(13, 30, 44);
  LocalDateTime localDateTime2 = LocalDateTime.of(localDate, localTime);
  System.out.println("LocalDateTime instance from date and time: " + localDateTime2);

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

  // Add and minus operations on LocalDateTime
  System.out.println("Add 1 yr, 1 month & 1 day to 2017-11-14: " + localDateTime.plusYears(1).plusMonths(1).plusDays(1));
  System.out.println("Minus 1 yr, 1 month & 1 day from 2017-11-14: " + localDateTime.minusYears(1).minusMonths(1).minusDays(1));
  System.out.println("Add 1 hour, 1 minute & 1 second to 13:45:30 = " + localDateTime.plusHours(1).plusMinutes(1).plusSeconds(1));
  System.out.println("Minus 1 hour, 1 minute & 1 second to 13:45:30 = " + localDateTime.minusHours(1).minusMinutes(1).minusSeconds(1));

  // Adjust the LocalDateTime
  System.out.println("Adjust 2017-11-14 into 2019-12-14: " + localDateTime.withYear(2019).withMonth(12));
  System.out.println("Adjust 13:45:30 into 15:30:30 = " + localDateTime.withHour(15).withMinute(30));

  // Adjust the LocalDateTime using TemporalAdjusters
  System.out.println("Adjust 2017-11-14 into first day of the month: " + localDateTime.with(TemporalAdjusters.firstDayOfMonth()));

  // Convert LocalDateTime to ZonedDateTime (date & time with timezone)
  ZonedDateTime zonedDateTime = localDateTime.atZone(ZoneId.of("Asia/Shanghai"));
  System.out.println("Convert LocalDateTime to ZonedDateTime: " + zonedDateTime);
 }
}
Output

Current local date and time: 2017-05-17T20:23:56.230
Local date & time from a given year, month, day, hour, minute & second: 2017-11-14T13:45:30
LocalDateTime instance from date and time: 2017-11-14T13:30:44
Get date: 2017-11-14
Get time: 13:45:30
Get year: 2017
Get month (enum): NOVEMBER
Get month: 11
Get day of month: 14
Get hour: 13
Get minute: 45
Get second: 30
Add 1 yr, 1 month & 1 day to 2017-11-14: 2018-12-15T13:45:30
Minus 1 yr, 1 month & 1 day from 2017-11-14: 2016-10-13T13:45:30
Add 1 hour, 1 minute & 1 second to 13:45:30 = 2017-11-14T14:46:31
Minus 1 hour, 1 minute & 1 second to 13:45:30 = 2017-11-14T12:44:29
Adjust 2017-11-14 into 2019-12-14: 2019-12-14T13:45:30
Adjust 13:45:30 into 15:30:30 = 2017-11-14T15:30:30
Adjust 2017-11-14 into first day of the month: 2017-11-01T13:45:30
Convert LocalDateTime to ZonedDateTime: 2017-11-14T13:45:30+08:00[Asia/Shanghai]



Tuesday, May 9, 2017

Java 8 Date and Time API: LocalTime


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

In this tutorial, you will learn:

  • How to create a LocalTime instance representing the current time
  • How to create a LocalTime instance from a given hour, minute and second
  • How to create a LocalTime instance from a given String
  • How to access the LocalTime properties (e.g. hour, minute, second)
  • How to perform plus and minus operations on LocalTime
  • How to remove time unit (e.g. seconds) from a LocalTime
Example

package com.melody.datetime;

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

public class LocalTimeDemo {

 public static void main(String[] args) {
  LocalTime currentLocalTime = LocalTime.now();
  System.out.println("Current local time: " + currentLocalTime);

  // Create a LocalTime instance from a given hour, minute and second
  LocalTime localTime = LocalTime.of(13, 30, 44);
  System.out.println("Local time from a given hour, minute & second: " + localTime);

  // Create a LocalTime instance from a given String
  LocalTime localTimeFromStr = LocalTime.parse("08:25:16");
  System.out.println("Local time from a given string: " + localTimeFromStr);

  // Access the LocalTime properties
  System.out.println("Get hour: " + localTime.getHour());
  System.out.println("Get minute: " + localTime.getMinute());
  System.out.println("Get second: " + localTime.getSecond());

  // Add and minus operations on LocalTime
  System.out.println("Add 1 hour, 1 minute & 1 second to 13:30:44 = " + localTime.plusHours(1).plusMinutes(1).plusSeconds(1));
  System.out.println("Minus 1 hour, 1 minute & 1 second to 13:30:44 = " + localTime.minusHours(1).minusMinutes(1).minusSeconds(1));

  // Adjust the LocalTime
  System.out.println("Adjust 13:30:44 into 15:45:44 = " + localTime.withHour(15).withMinute(45));

  // Remove the seconds unit from LocalTime
  System.out.println("Remove seconds from 13:30:44 = " + localTime.truncatedTo(ChronoUnit.MINUTES));
 }
}
Output

Current local time: 21:21:35.371
Local time from a given hour, minute & second: 13:30:44
Local time from a given string: 08:25:16
Get hour: 13
Get minute: 30
Get second: 44
Add 1 hour, 1 minute & 1 second to 13:30:44 = 14:31:45
Minus 1 hour, 1 minute & 1 second to 13:30:44 = 12:29:43
Adjust 13:30:44 into 15:45:44 = 15:45:44
Remove seconds from 13:30:44 = 13:30

Java 8 Date and Time API: LocalDate


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

In this tutorial, you will learn:
  • How to create a LocalDate instance representing the current date
  • How to create a LocalDate instance from a given year, month and day
  • How to access the LocalDate properties (e.g. month, year, day of week, etc.)
  • How to perform plus and minus operations on LocalDate
  • How to use TemporalAdjusters to adjust LocalDate
Example

package com.melody.datetime;

import java.time.LocalDate;
import java.time.Month;
import java.time.temporal.TemporalAdjusters;

public class LocalDateDemo {

 public static void main(String[] args) {
  LocalDate currentLocalDate = LocalDate.now();
  System.out.println("Current local date: " + currentLocalDate);

  // Create a LocalDate instance from a given year, month and day
  LocalDate localDate = LocalDate.of(2017, 11, 14);
  System.out.println("Local date from a given year, month & day: " + localDate);

  // Create a LocalDate instance from a given year, MONTH (enum) and day
  localDate = LocalDate.of(2017, Month.NOVEMBER, 14);
  System.out.println("Local date from a given year, MONTH (enum) & day: " + localDate);

  // Access the LocalDate properties
  System.out.println("Get year: " + localDate.getYear());
  System.out.println("Get month (enum): " + localDate.getMonth());
  System.out.println("Get month: " + localDate.getMonthValue());
  System.out.println("Get day of month: " + localDate.getDayOfMonth());
  System.out.println("Get day of year: " + localDate.getDayOfYear());
  System.out.println("Get day of week: " + localDate.getDayOfWeek());
  System.out.println("Get length of month: " + localDate.lengthOfMonth());
  System.out.println("Get length of year: " + localDate.lengthOfYear());
  System.out.println("Is leap year: " + localDate.isLeapYear());

  // Add and minus operations on LocalDate
  System.out.println("Add 1 yr, 1 month & 1 day to 2017-11-14: " + localDate.plusYears(1).plusMonths(1).plusDays(1));
  System.out.println("Minus 1 yr, 1 month & 1 day from 2017-11-14: " + localDate.minusYears(1).minusMonths(1).minusDays(1));

  // Adjust the LocalDate
  System.out.println("Adjust 2017-11-14 into 2019-12-14: " + localDate.withYear(2019).withMonth(12));

  // Adjust the LocalDate using TemporalAdjusters
  System.out.println("Adjust 2017-11-14 into first day of the month: " + localDate.with(TemporalAdjusters.firstDayOfMonth()));
 }
}

Output

Current local date: 2017-05-09
Local date from a given year, month & day: 2017-11-14
Local date from a given year, MONTH (enum) & day: 2017-11-14
Get year: 2017
Get month (enum): NOVEMBER
Get month: 11
Get day of month: 14
Get day of year: 318
Get day of week: TUESDAY
Get length of month: 30
Get length of year: 365
Is leap year: false
Add 1 yr, 1 month & 1 day to 2017-11-14: 2018-12-15
Minus 1 yr, 1 month & 1 day from 2017-11-14: 2016-10-13
Adjust 2017-11-14 into 2019-12-14: 2019-12-14
Adjust 2017-11-14 into first day of the month: 2017-11-01