Java Tutorials
LocalTime represents a time without a timezone information. Human readable format(HH:mm:ss) in terms of Hours,Minutes,Seconds and nano seconds, By Default hours are represented in 24hours format. If user has time in AM/PM format, it can be parased using parse factory method.
LocalTime tm = LocalTime.MAX; System.out.println(tm); 23:59:00.999999999 LocalTime tm =LocalTime.MIN; System.out.println(tm); 00:00 LocalTime tm = LocalTime.NOON; System.out.println(tm); 12:00
now method can be used to create LocalTime object,which returns system's time
LocalTime tm = LocalTime.now(); System.out.println(tm); 09:02:34.947022
If time represented in string format for example reading from text file or csv file or excel file, it can be easily converted into LocalTime object using parse method, as shown below
H hour of a day | 0-23 |
m minute | 0-59 |
s for second | 0-59 |
n nano of second | 0 |
N nano of the day | 0-999999999 |
K hour of am pm | 0-11 |
a am-pm-of day | PM |
Using Human readable format hours:minutes:seconds using default parse method LocalTime tm = LocalTime.parse("19:33:59") System.out.println(tm) 19:33:59 Parsing default format hours:minutes:seconds using DateTimeFormatter class DateTimeFormatter fmt = DateTimeFormatter.ofPattern("H:m:s") String str="12:55:59" LocalTime tm = LocalTime.parse(str,fmt) System.out.println(tm); 12:55:59 str="01:55:59 PM" Parsing hours:minutes:seconds AM/PM formatted data using DateTimeFormatter class DateTimeFormatter fmt = DateTimeFormatter.ofPattern("K:m:s a") LocalTime tm = LocalTime.parse(str,fmt) System.out.println(tm); 13:55:59
LocalTime object can be converted into seconds of the day. i.e seconds elapsed since day start(mid night)
toSecondOfDay() method used to convert LocalTime Object into seconds, as shown below
LocalTime tm = tm=LocalTime.now() System.out.println(tm) 18:48:56.618730 Convert LocalTime into seconds int seconds = tm.toSecondOfDay(); System.out.println(seconds) 67736 67736 seconds calculated as 18*60*60 +48*60 +56 = 67736 seconds 18 hours converted into seconds , every hour has 60 minutes, every minute has 60 seconds, so 18*60*60 48 minutes converted into seconds 48*60 plus 56 seconds
LocalTime object can be converted into string using DateTimeFormatter and format methods.
format(DateTimeFormatter) method used to convert LocalTime Object into String, as shown below
Converting 24-hour time format into AM/PM format.LocalTime tm = tm=LocalTime.now() System.out.println(tm) 18:48:56.618730 DateTimeFormatter fmt = DateTimeFormatter.ofPattern("K:m:s a") String str = tm.format(fmt); System.out.println(str); "6:48:56 PM" // 18:48:56.618730 converted into 6:48:56 PM format
ADS