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

No comments:

Post a Comment