How to use java8 LocalTime

preface

Java 8 has added many new features, such as LocalDate, LocalTime and LocalDateTime.

There are three new date categories:

Java.time.localdate - > process only the date of year, month and day

Default format: yyyy MM DD, for example: 2021-11-29

Java. Time. Localtime - > process only hours, minutes, seconds and nanoseconds

Default format: HH: mm: ss.sss, for example: 11:23:40.051942200.
When nanoseconds < = 0, nanoseconds are not displayed
When seconds < = 0 and nanoseconds < = 0, only hours and minutes are displayed by default, such as 11:23

Java.time.localdatetime - > it can process month, day, hour, minute and second at the same time

Default format: yyyy mm ddthh: mm: ss.sss for example: 2021-12-01T11:27:22.598224900

1: Create LocalTime

methodexplain
static LocalTime now()Returns the current time hour, minute, second, and nanosecond. The default format is HH: mm: ss.sss
static LocalTime now(ZoneId zone)Create a LocalTime instance by specifying the time zone
static LocalTime now(Clock clock)Create a LocalTime instance by specifying a clock
static LocalTime of(int hour, int minute)Create a LocalTime instance through hours and minutes. The output format is HH:mm. At this time, seconds and nanoseconds are not output by default
static LocalTime of(int hour, int minute, int second)Create LocalTime instances by hour, minute and second. The default output format is HH:mm:ss
static LocalTime of(int hour, int minute, int second, int nanoOfSecond)Create LocalTime instances through hours, minutes, seconds and nanoseconds. When nanoseconds > 0, nanoseconds are displayed; otherwise, nanoseconds are not displayed
static LocalTime ofSecondOfDay(long secondOfDay)Create LocalTime instance secondOfDay from the number of seconds in a day: from 0 to 24 * 60 * 60 – 1
static LocalTime ofNanoOfDay(long nanoOfDay)Create a LocalTime instance nanoOfDay from the number of nanoseconds in a day: from 0 to 24 * 60 * 60 * 1000000000 - 1
//Gets the current hour, minute, second, nanosecond
System.out.println(LocalTime.now()); //15:51:01.167526700
//Gets the time of the specified alarm clock
System.out.println(LocalTime.now(Clock.systemUTC()));//07:51:01.168523900 remarks: the utc time differs from the current time by 8 hours
//Gets the time in the specified time zone
System.out.println(LocalTime.now(ZoneId.systemDefault())); //15:51:01.168523900
//Obtain hours and minutes
System.out.println(LocalTime.of(13, 23));//13:23
//Get hour, minute and second
System.out.println(LocalTime.of(13, 23,23));//13:23:23
//Obtain hour, minute and second (when second = 0, second is not displayed by default, only HH:mm)
System.out.println(LocalTime.of(13, 23,0));//13:23
//Get hour, minute, second, nanosecond
System.out.println(LocalTime.of(13, 23,33,1));//13:23:33.000000001
//Obtain hour, minute, second and nanosecond (when nanosecond = 0, nanosecond is not displayed by default)
System.out.println(LocalTime.of(13, 23,0,0));//13:23
//Create LocalTime from seconds in a day
System.out.println(LocalTime.ofSecondOfDay(24*60));//00:24
//Create LocalTime from nanoseconds in a day
System.out.println(LocalTime.ofNanoOfDay(24*60));//00:00:00.000001440

2: LocalTime time comparison

methodexplain
boolean isAfter(LocalTime other)Is the comparison time after other
boolean isBefore(LocalTime other)Is the comparison time before other
int compareTo(LocalTime other)Time comparison localTimeA.compareTo(localTimeB), if equal, return 0; If a > b, return 1; Return - 1 if a < B

explain:
isAfter and isBefore can only compare before and after. When the values are equal, compareTo comparison is required

LocalTime before = LocalTime.parse("10:51:01.167526700");
LocalTime after = LocalTime.parse("15:51:01.167526700");
//Gets the current hour, minute, second, nanosecond
System.out.println(before.isAfter(after)); //false
System.out.println(before.isBefore(after)); //true

System.out.println(before.compareTo(after)); //-1
System.out.println(after.compareTo(before)); //1
System.out.println(before.compareTo(before)); //0

3: Get hour, minute, second, nanosecond

methodexplain
int getHour()Gets the hour and returns 0 to 23
int getMinute()Get minutes, return 0 to 59
int getSecond()Gets the second and returns 0 to 59
int getNano()Get nanoseconds and return 0 to 9999999
int get(TemporalField field)General method. You can obtain hours, minutes, seconds, milliseconds, nanoseconds by passing in the TemporalField object
long getLong(TemporalField field)General method. You can obtain hours, minutes, seconds, milliseconds, nanoseconds by passing in the TemporalField object
LocalTime now = LocalTime.parse("15:51:01.167526700");

//Get hours
System.out.println(now.getHour()); //15
//Get minutes
System.out.println(now.getMinute()); //51
//Get seconds
System.out.println(now.getSecond()); //1
//Get nanoseconds
System.out.println(now.getNano()); //167526700

//General Acquisition: obtain the equivalent of hour, minute, second and nanosecond by passing in the TemporalField object
System.out.println(now.get(ChronoField.HOUR_OF_DAY)); //15

4: Time calculation, plus / minus hours, minutes, seconds, nanoseconds

4.1. Plus / minus hours, minutes, seconds and nanoseconds

methodexplain
LocalTime plus(long amountToAdd, TemporalUnit unit)General method, which can increase nanosecond, microsecond, millisecond, second, minute and hour through unit parameter control
LocalTime plusHours(long hoursToAdd)Returns a copy of LocalTime with * hours added
LocalTime plusMinutes(long minutesToAdd)Returns a copy of LocalTime with * minutes added
LocalTime plusSeconds(long secondstoAdd)Returns a copy of LocalTime incremented by * seconds
LocalTime plusNanos(long nanosToAdd)Returns a copy of LocalTime with * nanoseconds added
LocalTime minus(long amountToSubtract, TemporalUnit unit)The general method can reduce nanosecond, microsecond, millisecond, second, minute and hour through unit parameter control
LocalTime minusHours(long hoursToSubtract)Returns a copy of LocalTime reduced by * hours
LocalTime minusMinutes(long minutesToSubtract)Returns a copy of LocalTime reduced by * minutes
LocalTime minusSeconds(long secondsToSubtract)Returns a copy of LocalTime reduced by * seconds
LocalTime minusNanos(long nanosToSubtract)Returns a copy of LocalTime reduced by * nanoseconds
LocalTime now = LocalTime.parse("10:51:01.167526700");
//LocalTime plus(long amountToAdd, TemporalUnit unit)  
//Currently, NANOS, MICROS, MILLIS, SECONDS, MINUTES, HOURS and half are available for unit in the api_ DAYS.  Other units are not available
System.out.println("Add 1 hour:"+now.plus(1, ChronoUnit.HOURS)); //11:51:01.167526700

System.out.println("Add 1 hour:"+now.plusHours(1));//11:51:01.167526700
System.out.println("Add 1 minute:"+now.plusMinutes(1));//10:52:01.167526700
System.out.println("Add 1 second:"+now.plusSeconds(1));//10:51:02.167526700
System.out.println("Increase by 1 nanosecond:"+now.plusNanos(1));//10:51:01.167526701

4.2. Calculate the interval between two times

Method 1:

Calculate the time difference between two localtimes through Duration

LocalTime start = LocalTime.parse("10:51:01.167526700");
LocalTime end = LocalTime.parse("15:52:03.167526701");

//The usage of between is the end start time. If the start time is greater than the end time, all values are negative
Duration duration = Duration.between(start, end);
System.out.println("The difference between the two times:"+duration.toSeconds()+"Seconds, difference:"+duration.toHours()+"Hours, difference:"+duration.toMinutes()+"minute");

result:
The difference between the two times: 18062 seconds, 5 hours and 301 minutes

Method 2:

Chrononunit can also calculate the difference between two units.
We use the between() method of the chrononunit class to perform the same operation

LocalTime start = LocalTime.parse("10:51:01.167526700");
LocalTime end = LocalTime.parse("15:52:03.167526701");

long seconds = ChronoUnit.SECONDS.between(start , end );
long hour = ChronoUnit.HOURS.between(start , end );
long minute = ChronoUnit.MINUTES.between(start , end );

System.out.println("The difference between the two times:"+seconds+"Seconds, difference:"+hour+"Hours, difference:"+minute+"minute");

result:
The difference between the two times: 18062 seconds, 5 hours and 301 minutes

Method 3:

Through the toSecondOfDay() method of LocalTime class, return the seconds corresponding to the time, and then calculate the interval between the two time differences

LocalTime start = LocalTime.parse("10:51:01.167526700");
LocalTime end = LocalTime.parse("15:52:03.167526701");

int time = end.toSecondOfDay() - start.toSecondOfDay();
System.out.println("The difference between the two times:"+time+"second");

result:
Difference between the two times: 18062 seconds

5: Time formatting

methodexplain
static LocalTime parse(CharSequence text)Get the LocalTime instance from the text string. The text format is generally 10:15 or 10:15:30
static LocalTime parse(CharSequence text, DateTimeFormatter formatter)Use a specific format to obtain the LocalTime instance from the text string. The format of text is generally consistent with that of formatter. For example, if text is in HH:mm format, the formatter should also be in HH:mm format, otherwise an error may be reported
String format(DateTimeFormatter formatter)Converts LocalTime to a specially formatted string
LocalTime time = LocalTime.parse("10:51:01.167526700");
System.out.println(time); //10:51:01.167526700

time = LocalTime.parse("10:51");
System.out.println(time);//10:51

time = LocalTime.parse("10:51:01");
System.out.println(time);//10:51:01

//If parse(CharSequence text, DateTimeFormatter formatter) is used, the text format must be consistent with the formatter format, otherwise an error may be reported
time = LocalTime.parse("10:51:01",DateTimeFormatter.ofPattern("HH:mm:ss"));
System.out.println(time);//10:51:01

String time1 = time.format(DateTimeFormatter.ofPattern("HH-mm-ss"));
System.out.println(time1); //10-51-01

6: LocalTime advanced

6.1 modify the hours, minutes, seconds and nanoseconds of LocalTime

methodexplain
LocalTime with(TemporalAdjuster adjuster)Use the passed TemporalAdjuster time adjuster as a parameter to adjust this date and time, and return a copy of the adjusted time after adjustment
LocalTime with(TemporalField field, long newValue)Used to set the specified field of LocalTime to a new value and return a copy of the new time. This method can be used to change any supported field, such as hour, minute, second. If the new value cannot be set because the field is not supported or for other reasons, an exception is thrown.
LocalTime withHour(int hour)Modify the hour of LocalTime variable, hour: from 0 to 23
LocalTime withMinute(int minute)Modify the minute of LocalTime variable, minute: from 0 to 59
LocalTime withSecond(int second)Modify the seconds of the LocalTime variable, second: from 0 to 59
LocalTime withNano(int nanoOfSecond)Modify the nanosecond of the LocalTime variable, nanoOfSecond: from 0 to 9999999

Use example:

LocalTime time = LocalTime.parse("10:51:03.167526700");
//Modify the hour of the LocalTime variable
System.out.println(time.withHour(1)); //01:51:03.167526700
//Minutes to modify the LocalTime variable
System.out.println(time.withMinute(1)); //10:01:03.167526700
//Modify the seconds of the LocalTime variable
System.out.println(time.withSecond(1)); //10:51:01.167526700
//Modify the nanosecond of the LocalTime variable
System.out.println(time.withNano(1)); //10:51:03.000000001

//Modify the seconds of the LocalTime variable
System.out.println(time.with(ChronoField.SECOND_OF_MINUTE, 1)); //10:51:01.167526700

Tags: java8

Posted on Fri, 03 Dec 2021 11:23:27 -0500 by edevil