$show=/label

Java 8 LocalTime Class With Examples

SHARE:

A quick guide to LocalTime class in Java 8 API. LocalTime class is an immutable class which deals with time part in date in simple way and 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:

COMMENTS

BLOGGER

About Us

Author: Venkatesh - I love to learn and share the technical stuff.
Name

accumulo,1,ActiveMQ,2,Adsense,1,API,37,ArrayList,17,Arrays,16,Bean Creation,3,Bean Scopes,1,BiConsumer,1,Blogger Tips,1,Books,1,C Programming,1,Collection,5,Collections,29,Collector,1,Command Line,1,Compile Errors,1,Configurations,7,Constants,1,Control Statements,8,Conversions,6,Core Java,93,Corona India,1,Create,2,CSS,1,Date,3,Date Time API,35,Dictionary,1,Difference,1,Download,1,Eclipse,2,Efficiently,1,Error,1,Errors,1,Exception,1,Exceptions,3,Fast,1,Files,14,Float,1,Font,1,Form,1,Freshers,1,Function,3,Functional Interface,2,Garbage Collector,1,Generics,4,Git,4,Grant,1,Grep,1,HashMap,1,HomeBrew,2,HTML,2,HttpClient,2,Immutable,1,Installation,1,Interview Questions,5,Iterate,2,Jackson API,3,Java,30,Java 10,1,Java 11,5,Java 12,5,Java 13,2,Java 14,2,Java 8,111,Java 8 Difference,2,Java 8 Stream Conversions,2,java 8 Stream Examples,3,Java 9,1,Java Conversions,11,Java Design Patterns,1,Java Files,1,Java Program,3,Java Programs,105,Java Spark,1,java.lang,5,java.util. function,1,jQuery,1,Kotlin,11,Kotlin Conversions,6,Kotlin Programs,10,Lambda,1,lang,29,Leap Year,1,live updates,1,LocalDate,1,Logging,1,Mac OS,2,Math,1,Matrix,5,Maven,1,Method References,1,Mockito,1,MongoDB,3,New Features,1,Operations,1,Optional,6,Oracle,5,Oracle 18C,1,Partition,1,Patterns,1,Programs,1,Property,1,Python,2,Quarkus,1,Read,1,Real Time,1,Recursion,2,Remove,2,Rest API,1,Schedules,1,Serialization,1,Servlet,2,Sort,1,Sorting Techniques,8,Spring,2,Spring Boot,23,Spring Email,1,Spring MVC,1,Streams,28,String,59,String Programs,12,String Revese,1,Swing,1,System,1,Tags,1,Threads,11,Tomcat,1,Tomcat 8,1,Troubleshoot,16,Unix,3,Updates,3,util,5,While Loop,1,
ltr
item
JavaProgramTo.com: Java 8 LocalTime Class With Examples
Java 8 LocalTime Class With Examples
A quick guide to LocalTime class in Java 8 API. LocalTime class is an immutable class which deals with time part in date in simple way and examples.
https://1.bp.blogspot.com/-EvNqcQNupo0/X71AGl_6mMI/AAAAAAAADFA/7A_YnDsiDWU_BRav6-YcTy319XuLxhwPwCLcBGAsYHQ/w400-h295/Java%2B8%2BLocalTime%2BClass%2BWith%2BExamples.png
https://1.bp.blogspot.com/-EvNqcQNupo0/X71AGl_6mMI/AAAAAAAADFA/7A_YnDsiDWU_BRav6-YcTy319XuLxhwPwCLcBGAsYHQ/s72-w400-c-h295/Java%2B8%2BLocalTime%2BClass%2BWith%2BExamples.png
JavaProgramTo.com
https://www.javaprogramto.com/2020/11/java-localtime.html
https://www.javaprogramto.com/
https://www.javaprogramto.com/
https://www.javaprogramto.com/2020/11/java-localtime.html
true
3124782013468838591
UTF-8
Loaded All Posts Not found any posts VIEW ALL Readmore Reply Cancel reply Delete By Home PAGES POSTS View All RECOMMENDED FOR YOU LABEL ARCHIVE SEARCH ALL POSTS Not found any post match with your request Back Home Sunday Monday Tuesday Wednesday Thursday Friday Saturday Sun Mon Tue Wed Thu Fri Sat January February March April May June July August September October November December Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec just now 1 minute ago $$1$$ minutes ago 1 hour ago $$1$$ hours ago Yesterday $$1$$ days ago $$1$$ weeks ago more than 5 weeks ago Followers Follow THIS PREMIUM CONTENT IS LOCKED STEP 1: Share to a social network STEP 2: Click the link on your social network Copy All Code Select All Code All codes were copied to your clipboard Can not copy the codes / texts, please press [CTRL]+[C] (or CMD+C with Mac) to copy Table of Content