Pages

Tuesday, November 24, 2020

Java 8 LocalTime Class With Examples

1. Overview


In this article, you'll learn how to use LocalTime API in java 8 with example programs.

LocalTime is an immutable class that deals date and time object but is represents only time part of date and can be viewed as hour-minute-seconds.

Advantage of immutable class is that this can be operated with multiple threads so it is thread-safe.

If you want to store only the time data then this class is the right choice.

Java 8 LocalTime Class With Examples


2. Java 8 LocalTime Class

LocalTime is final class and implements Temporal, TemporalAdjuster, Comparable<LocalTime>, Serializable interfaces.

This follows the ISO-8601 calendar system without timezone.

Below are the methods that are used regularly by the developers.

public static LocalTime now(): This is used to create the time object by getting the current time with the default timezone.

public static LocalTime of(int hour, int minute, int second): This is also used to create the localtime object with the given time parameters.

LocalDateTime atDate(LocalDate date): It is used to combine this time with a date to create a LocalDateTime.

int compareTo(LocalTime other): It is used to compare this time to another time.

String format(DateTimeFormatter formatter): It is used to format this time using the specified formatter.

int get(TemporalField field): It is used to get the value of the specified field from this time as an int.

LocalTime minusHours(long hoursToSubtract): It is used to return a copy of this LocalTime with the specified number of hours subtracted.

LocalTime minusMinutes(long minutesToSubtract): It is used to return a copy of this LocalTime with the specified number of minutes subtracted.

LocalTime plusHours(long hoursToAdd): It is used to return a copy of this LocalTime with the specified number of hours added.

LocalTime plusMinutes(long minutesToAdd): It is used to return a copy of this LocalTime with the specified number of minutes added.

public String format(DateTimeFormatter formatter): It is used to convert LocalTime to String.

public long until(Temporal endExclusive, TemporalUnit unit): It is sued to calculates the amount of time until another time in terms of the specified unit.

public LocalTime truncatedTo(TemporalUnit unit): Truncation returns a copy of the original time with fields smaller than the specified unit set to zero. For example, truncating with the minutes unit will set the second-of-minute and nano-of-second field to zero.

public boolean isAfter(LocalTime other): It is used to check if this time is after the specified time.

public boolean isBefore(LocalTime other): It is used to check if this time is before the specified time.

public int compareTo(LocalTime other): This is used to compare this time to another time.



3. Java 8 LocalTime Examples


Next, let us use all the methods from LocalTime class along with the simple example programs.


3.1 Example 1: LocalTime Object Creation


LocalTime object can be created using two methods and those are now() and of() method.
now() method gets the time from the current system time with nano seconds where as of(int hours, int mins, int secs) method creates the time part from the given values.
package com.javaprogramto.java8.dates.localtime;

import java.time.LocalTime;

public class LocalTimeCreationExample {
	public static void main(String[] args) {

		// LocalTime object creation

		// Example 1 : Using now() method to get the current time
		LocalTime time1 = LocalTime.now();
		System.out.println("Time 1 using now() : " + time1);

		// Example 2 : Using of() method
		LocalTime time2 = LocalTime.of(20, 20, 20);
		System.out.println("Time 2 using of() : " + time2);

		// Example 3 : Using of() method
		LocalTime time3 = LocalTime.of(3, 30);
		System.out.println("Time 3 using of() : " + time3);
	}
}
 
Output:
Time 1 using now() : 21:21:58.526563
Time 2 using of() : 20:20:20
Time 3 using of() : 03:30
 

3.2 Example 2: Getting Time Parts from LocalTime Object


LocalTime class has a handy methods to get the hours, minutes and seconds from the local time object using getHour(), getMinute(), getSecond() methods.
package com.javaprogramto.java8.dates.localtime;

import java.time.LocalTime;

public class LocalTimeCreationExample {
	public static void main(String[] args) {

		// LocalTime object - creating from current time.
		LocalTime time = LocalTime.now();
		System.out.println("Current time : "+time);
		
		// Example 1 : Getting the hour from time.
		System.out.println("Hour : " + time.getHour());

		// Example 2 : Getting the minutes from time.
		System.out.println("Minutes : " + time.getMinute());

		// Example 3 : Getting the seconds from time.
		System.out.println("Seconds : " + time.getSecond());
	}
}
 
Output:
Current time : 21:30:08.328088
Hour : 21
Minutes : 30
Seconds : 8
 

3.3 Example 3: Working with LocalTime Timezones


Is there a way to create the LocalTime with time zones? yes, we can pass the timezone to now() method.

Look at the below examples.

First, created two timezones instances from ZoneId and passed the timezone to LocalTime.now() method.
Then, next obtained the difference between two timezone dates in hours and seconds.
package com.javaprogramto.java8.dates.localtime;

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

public class LocalTimeCreationExample {
	public static void main(String[] args) {

		// Getting the Los Angeles id from ZoneId.
		ZoneId zoneLosAngeles = ZoneId.of("America/Los_Angeles");

		// Getting the Amsterdam id from ZoneId.
		ZoneId zoneAmsterdam = ZoneId.of("Europe/Amsterdam");

		// LocalTime object with timezone 1
		LocalTime timeLosAngeles = LocalTime.now(zoneLosAngeles);
		System.out.println("timeLosAngeles : " + timeLosAngeles);

		// LocalTime object with timezone 2
		LocalTime timeAmsterdam = LocalTime.now(zoneAmsterdam);
		System.out.println("timeAmsterdam : " + timeAmsterdam);

		// Getting the time differences between these two times in hours
		long diffInHours = ChronoUnit.HOURS.between(timeLosAngeles, timeAmsterdam);
		System.out.println("Time diff in hours : "+diffInHours);
		
		// Getting the time differences between these two times in seconds
		long diffInSeconds = ChronoUnit.SECONDS.between(timeLosAngeles, timeAmsterdam);
		System.out.println("Time diff in seconds : "+diffInSeconds);
	}
}
 
Output:
timeLosAngeles : 08:13:09.492711
timeAmsterdam : 17:13:09.495475
Time diff in hours : 9
Time diff in seconds : 32400
 

3.4 Example 4: Formatting LocalTime to String


Example program on to convert LocalTime to String value. Time pattern can be created using DateTimeFormatter.ofPattern() and pass this pattern to format() method. 
package com.javaprogramto.java8.dates.localtime;

import java.time.LocalTime;
import java.time.format.DateTimeFormatter;

public class LocalTimeFormatExample {
	public static void main(String[] args) {

		// LocalTime object with the current time
		LocalTime currentTime = LocalTime.now();
		System.out.println("Current Time : " + currentTime);

		// converting DateTime to String in format "hh:mm:ss"
		String timeInString = currentTime.format(DateTimeFormatter.ofPattern("hh:mm:ss"));
		System.out.println("time 1 in string : " + timeInString);

		// converting DateTime to String in format "hh:mm:ss a"
		String time2InString = currentTime.format(DateTimeFormatter.ofPattern("hh:mm:ss a"));
		System.out.println("Time 2 in string : " + time2InString);
	}
}
 
Output:
Current Time : 21:59:28.682714
time 1 in string : 09:59:28
Time 2 in string : 09:59:28 PM
 

3.5 Example 5: Adding and Misusing (subtract) Time Values using LocalTime


Use plusHours(), plusMinutes() and plusSeconds() methods to plus the time values.

package com.javaprogramto.java8.dates.localtime;

import java.time.LocalTime;

public class LocalTimeAddSubtractExample {
	public static void main(String[] args) {

		// LocalTime object with the current time
		LocalTime currentTime = LocalTime.of(10,20,30);
		System.out.println("Current Time : " + currentTime);

		// Adding time to the current time
		LocalTime timeHoursAdded = currentTime.plusHours(1);
		LocalTime timeMinsAdded = currentTime.plusMinutes(10);
		LocalTime timeSecsAdded = currentTime.plusSeconds(60);

		System.out.println("timeHoursAdded : " + timeHoursAdded);
		System.out.println("timeMinsAdded : " + timeMinsAdded);
		System.out.println("timeSecsAdded : " + timeSecsAdded);
	}
}
 
Output:
Current Time : 10:20:30
timeHoursAdded : 11:20:30
timeMinsAdded : 10:30:30
timeSecsAdded : 10:21:30
 
Use minusHours(), minusMinutes() and minusSeconds() to subtract the time from LocalTime objects.
package com.javaprogramto.java8.dates.localtime;

import java.time.LocalTime;

public class LocalTimeAddSubtractExample {
	public static void main(String[] args) {

		// LocalTime object with the current time
		LocalTime currentTime = LocalTime.of(10,20,30);
		System.out.println("Current Time : " + currentTime);

		// Substracting time to the current time
		LocalTime timeHoursSubstracted = currentTime.minusHours(1);
		LocalTime timeMinsSubstracted = currentTime.minusMinutes(10);
		LocalTime timeSecsSubstracted = currentTime.minusSeconds(60);

		System.out.println("timeHoursSubstracted : " + timeHoursSubstracted);
		System.out.println("timeMinsSubstracted : " + timeMinsSubstracted);
		System.out.println("timeSecsSubstracted : " + timeSecsSubstracted);			
	}
}
 
Output:
Current Time : 10:20:30
timeHoursSubstracted : 09:20:30
timeMinsSubstracted : 10:10:30
timeSecsSubstracted : 10:19:30
 

3.6 Example 6: LocalTime until(), truncatedTo() and compareTo(), isAfter(), isBefore() Methods


package com.javaprogramto.java8.dates.localtime;

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

public class LocalTimeOtherMethodsExample {
	public static void main(String[] args) {

		// LocalTime object with the current time
		LocalTime currentTime = LocalTime.now();
		System.out.println("Current Time : " + currentTime);

		LocalTime nextTime = LocalTime.of(12, 59);
		System.out.println("next time : "+nextTime);

		// until() example - to compute the time diff.
		long hours = nextTime.until(currentTime, ChronoUnit.HOURS);
		System.out.println("untill hours : "+hours);
		
		// truncatedTo() example - to get the time limited to a specifed unit of time.
		LocalTime truncatedHours = currentTime.truncatedTo(ChronoUnit.HOURS);
		System.out.println("LocalTime truncated to hours : "+truncatedHours);
		
		// comparing times part
		int isSame = currentTime.compareTo(nextTime);
		
		if(isSame == 0) {
			System.out.println("currentTime and nextTime are same");
		} else {
			System.out.println("currentTime and nextTime are not same");
		}
	
		if(currentTime.isAfter(nextTime)) {
			System.out.println("currentTime is after nextTime");
		} else {
			System.out.println("currentTime is not after nextTime");
		}
		
		if(currentTime.isBefore(nextTime)) {
			System.out.println("currentTime is before nextTime");
		} else {
			System.out.println("currentTime is not before nextTime");
		}
		
	}
}
 
Output:
Current Time : 22:34:25.272566
next time : 12:59
untill hours : 9
LocalTime truncated to hours : 22:00
currentTime and nextTime are not same
currentTime is after nextTime
currentTime is not before nextTime
 

4. Conclusion


In this article, you've seen about the java 8 LocalTime class and its mostly used methods with examples.

GitHub:


Read Next:

No comments:

Post a Comment

Please do not add any spam links in the comments section.