This is the second day of my participation in the Gwen Challenge in November. Check out the details: The last Gwen Challenge in 2021.”
❤️ Author profile: Java quality creator 🏆, CSDN blog expert certification 🏆, Huawei Cloud enjoy expert certification 🏆
❤️ technology live, the appreciation
❤️ like 👍 collect ⭐ look again, form a habit
Hello, I’m Xiao Xu Zhu. A few days ago, a fan asked me if I could sort out the new date and time API (jsr-310) for JAVA8. The answer is yes, I’m a fan. Because the content is partial, will tear down many to write.
So much for the gossip, please look at the text below.
An introduction to the commonly used date and time apis
This section describes the datetime apis commonly used by the java8API, in order of java.time package classes:
- Clock, the Clock
- Instant: Instant time.
- LocalDate: indicates the LocalDate. Only year month day
- LocalDateTime: indicates the LocalDate and time. LocalDate+LocalTime
- LocalTime: indicates the LocalTime
- OffsetDateTime: date time with time offset (not including ZoneRegion based time offset)
- OffsetTime: Indicates the time with time offset
- ZonedDateTime: date time with time offset (including ZoneRegion based time offset)
The blogger clicked on all of these classes, which are immutable. It is also officially stated that classes in the java.time package are thread-safe.
Clock
Clock class description
public abstract class Clock {... }Copy the code
Clock is an abstract class that provides four inner classes, which are its internal implementation classes
- FixedClock: A clock that always returns the same moment, often used for testing.
- OffsetClock: indicates the OffsetClock, in the unit of Duration.
- SystemClock: indicates the default local clock.
- TickClock: indicates the offset clock in nanosecond.
Clock provides the following common methods (which have corresponding implementations in the implementation class) :
// Get the current Instant object of the clock. Public abstract Instant Instant () public long millis() public long millis() // Gets the time zone used to create the clock. Public abstract Clock withZone(ZoneId zone) public abstract Clock withZone(ZoneId zone)Copy the code
FixedClock
Clock.fixed
public static Clock fixed(Instant fixedInstant, ZoneId zone)
Copy the code
Instant and zone need to be passed, and a clock with a fixed instant will be returned.
Instant instant = Instant.now();
Clock fixedClock = Clock.fixed(instant, ZoneId.of("Asia/Shanghai"));
Clock fixedClock1 = Clock.fixed(instant, ZoneId.of("GMT"));
System.out.println(Chinese time zone Clock:+fixedClock);
System.out.println("GMT Clock:"+fixedClock1);
Copy the code
According to the run result, the returned result has the corresponding time zone.
Verify that the acquired clock will not change:
Clock clock = Clock.systemDefaultZone();
Clock fixedClock = Clock.fixed(clock.instant(), ZoneId.of("Asia/Shanghai"));
System.out.println(fixedClock.instant());
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(fixedClock.instant());
Copy the code
Clock.fixed Creates a fixed Clock. The Clock object will always provide the same time as specified. As shown in the picture, sleep is forced for 1 second, but the time does not change.
Fixed is more compatible with the Offset method
C) clock. fixed d) adding time or subtracting time
Sample code is as follows
Clock clock = Clock.systemDefaultZone();
Clock fixedClock = Clock.fixed(clock.instant(), ZoneId.of("Asia/Shanghai"));
System.out.println(fixedClock.instant());
Clock clockAdd = Clock.offset(clock, Duration.ofMinutes(20));
Clock clockSub = Clock.offset(clock, Duration.ofMinutes(-10));
System.out.println("Original:" + clock.instant());
System.out.println("Twenty minutes added:" + clockAdd.instant());
System.out.println("Ten minutes off:" + clockSub.instant());
Copy the code
OffsetClock
OffsetClock is the OffsetClock, and the offset is Duration.
//Clock
public static Clock offset(Clock baseClock, Duration offsetDuration) {
Objects.requireNonNull(baseClock, "baseClock");
Objects.requireNonNull(offsetDuration, "offsetDuration");
if (offsetDuration.equals(Duration.ZERO)) {
return baseClock;
}
return new OffsetClock(baseClock, offsetDuration);
}
Copy the code
Offset method returns the OffsetClock instance object
Clock clock = Clock.systemDefaultZone();
Clock fixedClock = Clock.fixed(clock.instant(), ZoneId.of("Asia/Shanghai"));
System.out.println(fixedClock.instant());
Clock clockAdd = Clock.offset(clock, Duration.ofMinutes(20));
System.out.println("Original:" + clock.instant());
System.out.println("Twenty minutes added:" + clockAdd.instant());
Copy the code
SystemClock
SystemClock is the system’s default local clock.
Clock clock = Clock.systemDefaultZone();
System.out.println(clock.millis());
Clock utc = Clock.systemUTC();
System.out.println(utc.millis());
System.out.println(System.currentTimeMillis());
Copy the code
It’s exactly the same. This is to see the source code
Clock.systemDefaultZone()
Use the system’s default time zone zoneid.systemDefault ()
public static Clock systemDefaultZone() {
return new SystemClock(ZoneId.systemDefault());
}
Copy the code
The final call is also system.CurrentTimemillis ()
Clock.systemUTC()
The UTC time zone is zoneoffset.UTC
public static Clock systemUTC(a) {
return new SystemClock(ZoneOffset.UTC);
}
Copy the code
The final call is also system.CurrentTimemillis ()
conclusion
The millis() timestamp obtained by clock. systemDefaultZone() is the same as that obtained by clock. systemUTC().
TickClock
TickClock is an offset clock. The minimum unit of time offset is nanosecond.
As you can see, Clock provides three main methods
// The time unit of the constructed clock is a custom offset unit
public static Clock tick(Clock baseClock, Duration tickDuration);
// The clock is constructed in minutes
public static Clock tickMinutes(ZoneId zone);
// The clock is constructed in seconds
public static Clock tickSeconds(ZoneId zone) ;
Copy the code
Practical:
Clock tickClock = Clock.tick(Clock.systemDefaultZone(),Duration.ofHours(1L));
Clock tickMinutes = Clock.tickMinutes(ZoneId.of("Asia/Shanghai"));
Clock tickSeconds = Clock.tickSeconds(ZoneId.of("Asia/Shanghai"));
LocalDateTime tickClockLocalDateTime = LocalDateTime.ofInstant(Instant.ofEpochMilli(tickClock.millis()),ZoneId.of("Asia/Shanghai"));
LocalDateTime tickMinutesLocalDateTime = LocalDateTime.ofInstant(Instant.ofEpochMilli(tickMinutes.millis()),ZoneId.of("Asia/Shanghai"));
LocalDateTime tickSecondsLocalDateTime = LocalDateTime.ofInstant(Instant.ofEpochMilli(tickSeconds.millis()),ZoneId.of("Asia/Shanghai"));
System.out.println("tickClock :"+tickClock.millis() +"Convert to date time:"+tickClockLocalDateTime);
System.out.println("tickMinutes:"+tickMinutes.millis() +"Convert to date time:"+tickMinutesLocalDateTime);
System.out.println("tickSeconds:"+tickSeconds.millis() +"Convert to date time:"+tickSecondsLocalDateTime);
Copy the code
Offset units supported: days, hours, minutes, seconds, haoseconds, nanoseconds
Instant
Instant class description
public final class Instant
implements Temporal.TemporalAdjuster.Comparable<Instant>, Serializable {... }Copy the code
Instant means Instant time. Is also immutable and thread-safe. The java.time package is actually thread-safe.
Instant is a new feature in Java 8 with two core fields
.private final long seconds;
private final intnanos; .Copy the code
One is a timestamp in seconds and the other is a timestamp in nanoseconds.
** System.currentTimemillis () returns a millisecond timestamp, while system.currentTimemillis () returns a millisecond timestamp.
Instant Common usage
Instant now = Instant.now();
System.out.println("now:"+now);
System.out.println(now.getEpochSecond()); / / SEC.
System.out.println(now.toEpochMilli()); / / ms
Copy the code
Instant does not have a time zone, but with time zone added Instant can be converted to ZonedDateTime
Instant ins = Instant.now();
ZonedDateTime zdt = ins.atZone(ZoneId.systemDefault());
System.out.println(zdt);
Copy the code
The long timestamp goes to Instant
Note that the time unit of the long timestamp is the method transformation corresponding to Instant
//1626796436 is a second-level timestamp
Instant ins = Instant.ofEpochSecond(1626796436);
ZonedDateTime zdt = ins.atZone(ZoneId.systemDefault());
System.out.println("Second timestamp conversion:"+zdt);
//1626796436111l is a second-level timestamp
Instant ins1 = Instant.ofEpochMilli(1626796436111l);
ZonedDateTime zdt1 = ins1.atZone(ZoneId.systemDefault());
System.out.println("Millisecond timestamp conversion:"+zdt1);
Copy the code
The pit of Instant
Instant. Now () is 8 time zones different from Beijing time. This is a detail to avoid.
Look at the source code, in UTC time.
public static Instant now(a) {
return Clock.systemUTC().instant();
}
Copy the code
Solution:
Instant now = Instant.now().plusMillis(TimeUnit.HOURS.toMillis(8));
System.out.println("now:"+now);
Copy the code
LocalDate
LocalDate class description
LocalDate indicates the LocalDate. Only year month day. The value is equivalent to YYYY-MM-DD.
Common usage of LocalDate
Get the current date
LocalDate localDate1 = LocalDate.now();
LocalDate localDate2 = LocalDate.now(ZoneId.of("Asia/Shanghai"));
LocalDate localDate3 = LocalDate.now(Clock.systemUTC());
System.out.println("now :"+localDate1);
System.out.println("now by zone :"+localDate2);
System.out.println("now by Clock:"+localDate3);
Copy the code
Get the localDate object
LocalDate localDate1 = LocalDate.of(2021.8.14);
LocalDate localDate2 = LocalDate.parse("2021-08-14");
System.out.println(localDate1);
System.out.println(localDate2);
Copy the code
Gets the year, month and day of the specified date
LocalDate localDate1 = LocalDate.of(2021, 8, 14); // Current date year: 2021 System.out.println(localDate1.getYear()); AUGUST System.out.println(localDate1.getMonth())); Println (localDatE1.getMonthValue ()); // Current month: 8 System.out.println(localDate1.getMonthValue()); // The date is the day of the current week :6 system.out.println (localDate1.getDayofweek ().getValue()); // The date is the day of the current month :14 system.out.println (localDate1.getDayofMonth ()); // The date is the day of the current year :226 system.out.println (localDate1.getDayofYear ());Copy the code
Modify the year, month and day
LocalDate localDate1 = LocalDate.of(2021.8.14);
// Modify the year of the date: 2022-08-14
System.out.println(localDate1.withYear(2022));
// Modify the date month: 2021-12-14
System.out.println(localDate1.withMonth(12));
// Change the number of days in the current month: 2021-08-01
System.out.println(localDate1.withDayOfMonth(1));
Copy the code
Comparing the date
LocalDate localDate1 = LocalDate.of(2021, 8, 14); Int I = localDate1.compareTo(localdate.of (2021, 8, 1)); System.out.println(i); Println (localdate1.isbefore (localdate.of (2021,8,31))); Println (localdate1.isafter (localdate.of (2021,8,31))); false system.out.println (localdate1.isafter (localdate.of (2021,8,31)); Println (localDate1.isequal (localDate.of (2021, 8, 14)));Copy the code
LocalDate and String convert to each other, and Date and LocalDate convert to each other
LocalDate and String convert to each other
LocalDate localDate1 = LocalDate.of(2021.8.14);
/ / LocalDate String
DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
String dateString = localDate1.format(dateTimeFormatter);
System.out.println("Turn LocalDate String."+dateString);
/ / String LocalDate
String str = "2021-08-14";
DateTimeFormatter fmt = DateTimeFormatter.ofPattern("yyyy-MM-dd");
LocalDate date = LocalDate.parse(str, fmt);
System.out.println("String turned LocalDate:"+date);
Copy the code
Date and LocalDate are converted to each other
/ / Date LocalDate
Date now = new Date();
// Convert Date to ZonedDateTime
Instant instant = now.toInstant();
ZonedDateTime zonedDateTime = instant.atZone(ZoneId.of("Asia/Shanghai"));
LocalDate localDate = zonedDateTime.toLocalDate();
// Sat Aug 14 23:16:28 CST 2021
System.out.println(now);
/ / 2021-08-14
System.out.println(localDate);
/ / LocalDate Date
LocalDate now1 = LocalDate.now();
ZonedDateTime dateTime = now1.atStartOfDay(ZoneId.of("Asia/Shanghai"));
Date date1 = Date.from(dateTime.toInstant());
System.out.println(date1);
Copy the code
LocalDateTime
LocalDateTime class description
Indicates the current date and time. The value is yyyY-MM-DDTHh: MM :ss
Common usage of LocalDateTime
Gets the current date and time
LocalDate d = LocalDate.now(); // The current date
LocalTime t = LocalTime.now(); // The current time
LocalDateTime dt = LocalDateTime.now(); // Current date and time
System.out.println(d); // Print strictly in ISO 8601 format
System.out.println(t); // Print strictly in ISO 8601 format
System.out.println(dt); // Print strictly in ISO 8601 format
Copy the code
The local date and time retrieved from now() is always returned with the current default time zone, depending on the run result
Gets the specified date and time
LocalDate d2 = LocalDate.of(2021.07.14); // 2021-07-14, note that 07=07 months
LocalTime t2 = LocalTime.of(13.14.20); / / 13:14:20
LocalDateTime dt2 = LocalDateTime.of(2021.07.14.13.14.20);
LocalDateTime dt3 = LocalDateTime.of(d2, t2);
System.out.println("Specified date and time:"+dt2);
System.out.println("Specified date and time:"+dt3);
Copy the code
Date and time addition and subtraction and modification
LocalDateTime currentTime = LocalDateTime.now(); // Current date and time
System.out.println("-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- time addition and subtraction and modification -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --");
//3.LocalDateTime addition and subtraction include all LocalDate and LocalTime additions and subtractions
System.out.println("3. Current time:" + currentTime);
System.out.println("3. Current time plus 5 years:" + currentTime.plusYears(5));
System.out.println("3. Current time plus 2 months:" + currentTime.plusMonths(2));
System.out.println("3. Current time minus 2 days:" + currentTime.minusDays(2));
System.out.println("3. Current time minus 5 hours:" + currentTime.minusHours(5));
System.out.println("3. Current time plus 5 minutes:" + currentTime.plusMinutes(5));
System.out.println("3. Current time plus 20 seconds:" + currentTime.plusSeconds(20));
// Add a year back, subtract a day forward, add 2 hours back, subtract 5 minutes forward
System.out.println("3. At the same time (add one year back, subtract one day forward, add two hours back, subtract five minutes forward) :" + currentTime.plusYears(1).minusDays(1).plusHours(2).minusMinutes(5));
System.out.println("3. Modified year to 2025:" + currentTime.withYear(2025));
System.out.println("3. Modify month to December:" + currentTime.withMonth(12));
System.out.println("3. Modification date: 27th:" + currentTime.withDayOfMonth(27));
System.out.println("3. Change the hour to 12:" + currentTime.withHour(12));
System.out.println("3. Change the minutes to 12:" + currentTime.withMinute(12));
System.out.println("3. Change the seconds to 12:" + currentTime.withSecond(12));
Copy the code
LocalDateTime and Date are converted to each other
Turn the Date LocalDateTime
System.out.println("-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- method one: write step by step -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --");
// Instantiate a time object
Date date = new Date();
// Returns the instant representing the same point on the timeline as the date object
Instant instant = date.toInstant();
// Obtain the default system time zone
ZoneId zoneId = ZoneId.systemDefault();
// Get the date and time with time zone based on time zone
ZonedDateTime zonedDateTime = instant.atZone(zoneId);
// Convert to LocalDateTime
LocalDateTime localDateTime = zonedDateTime.toLocalDateTime();
System.out.println("Method 1: Date =" + date);
System.out.println(Method 1: LocalDateTime =" + localDateTime);
System.out.println("-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- method 2: one pace reachs the designated position (recommended) -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --");
// Instantiate a time object
Date todayDate = new Date();
// instant.ofepochmilli (long L) uses milliseconds in epoch 1970-01-01t00:00:00 Z to get an instance of Instant
LocalDateTime ldt = Instant.ofEpochMilli(todayDate.getTime()).atZone(ZoneId.systemDefault()).toLocalDateTime();
System.out.println(Date = Date = Date + todayDate);
System.out.println("LocalDateTime =" + ldt);
Copy the code
LocalDateTime transfer Date
System.out.println("-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- method one: write step by step -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --");
// Get LocalDateTime, the current time
LocalDateTime localDateTime = LocalDateTime.now();
// Obtain the default system time zone
ZoneId zoneId = ZoneId.systemDefault();
// Get the date and time with time zone based on time zone
ZonedDateTime zonedDateTime = localDateTime.atZone(zoneId);
// Returns the instant representing the same point on the timeline as the date object
Instant instant = zonedDateTime.toInstant();
// Convert to Date
Date date = Date.from(instant);
System.out.println(LocalDateTime = LocalDateTime + localDateTime);
System.out.println("Method 1: Convert Date =" + date);
System.out.println("-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- method 2: one pace reachs the designated position (recommended) -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --");
Instantiate a LocalDateTime object
LocalDateTime now = LocalDateTime.now();
// Convert to date
Date dateResult = Date.from(now.atZone(ZoneId.systemDefault()).toInstant());
System.out.println(LocalDateTime = LocalDateTime + now);
System.out.println("Method 2: Convert Date =" + dateResult);
Copy the code
LocalTime
LocalTime class description
LocalTime: indicates the LocalTime
Common usage of LocalTime
Get the current time
LocalTime localTime1 = LocalTime.now();
LocalTime localTime2 = LocalTime.now(ZoneId.of("Asia/Shanghai"));
LocalTime localTime3 = LocalTime.now(Clock.systemDefaultZone());
System.out.println("now :"+localTime1);
System.out.println("now by zone :"+localTime2);
System.out.println("now by Clock:"+localTime3);
Copy the code
Get the LocalTime object
LocalTime localTime1 = LocalTime.of(23.26.30);
LocalTime localTime2 = LocalTime.of(23.26);
System.out.println(localTime1);
System.out.println(localTime2);
Copy the code
Gets the time and second of the specified date
LocalTime localTime1 = LocalTime.of(23.26.30);
// Current time: 23
System.out.println(localTime1.getHour());
// The current time is 26 minutes
System.out.println(localTime1.getMinute());
// The current time in seconds: 30
System.out.println(localTime1.getSecond());
Copy the code
Change time minute second
LocalTime localTime1 = LocalTime.of(23.26.30);
// Change time: 00:26:30
System.out.println(localTime1.withHour(0));
// Change the minute of the time: 23:30:30
System.out.println(localTime1.withMinute(30));
// Change the time in seconds: 23:26:59
System.out.println(localTime1.withSecond(59));
Copy the code
More time
LocalTime localTime1 = LocalTime.of(23.26.30);
LocalTime localTime2 = LocalTime.of(23.26.32);
// Return 0:-1; // Return 0:-1
System.out.println(localTime1.compareTo(localTime2));
// Compares whether the specified time is earlier than the parameter time (true is earlier) :true
System.out.println(localTime1.isBefore(localTime2));
// Compares whether the specified time is later than the parameter time (true is later) :false
System.out.println(localTime1.isAfter(localTime2));
// Compare whether two times are equal :true
System.out.println(localTime1.equals(LocalTime.of(23.26.30)));
Copy the code
OffsetDateTime
OffsetDateTime class description
OffsetDateTime: date time with time offset (not including ZoneRegion based time offset)
public final class OffsetDateTime
implements Temporal.TemporalAdjuster.Comparable<OffsetDateTime>, Serializable {
//The minimum supported {@code OffsetDateTime}, '-999999999-01-01T00:00:00+18:00'
public static final OffsetDateTime MIN = LocalDateTime.MIN.atOffset(ZoneOffset.MAX);
// The maximum supported {@code OffsetDateTime}, '+ 9999999-12-31T23:59:59.9999999-18:00 '.
public static finalOffsetDateTime MAX = LocalDateTime.MAX.atOffset(ZoneOffset.MIN); . }Copy the code
MIN and MAX above are public static variables.
OffsetDateTime Common usage
Gets the current date and time
OffsetDateTime offsetDateTime1 = OffsetDateTime.now();
OffsetDateTime offsetDateTime2 = OffsetDateTime.now(ZoneId.of("Asia/Shanghai"));
OffsetDateTime offsetDateTime3 = OffsetDateTime.now(Clock.systemUTC());
System.out.println("now :"+offsetDateTime1);
System.out.println("now by zone :"+offsetDateTime2);
System.out.println("now by Clock:"+offsetDateTime3);
Copy the code
Gets the OffsetDateTime object
LocalDateTime localDateTime1 = LocalDateTime.of(2021.8.15.13.14.20);
OffsetDateTime offsetDateTime1 = OffsetDateTime.of(localDateTime1, ZoneOffset.ofHours(8));
OffsetDateTime offsetDateTime2 = OffsetDateTime. of(2021.8.15.13.14.20.0, ZoneOffset.ofHours(8));
Instant now = Instant.now();
OffsetDateTime offsetDateTime3 = OffsetDateTime.ofInstant(now, ZoneId.of("Asia/Shanghai"));
System.out.println(offsetDateTime1);
System.out.println(offsetDateTime2);
System.out.println(offsetDateTime3);
Copy the code
Gets the year, month, day, hour, minute, second of the specified date
LocalDateTime localDateTime1 = LocalDateTime.of(2021.8.15.13.14.20);
OffsetDateTime offsetDateTime1 = OffsetDateTime.of(localDateTime1, ZoneOffset.ofHours(8));
// Current year: 2021
System.out.println(offsetDateTime1.getYear());
// Month of the current time: 8
System.out.println(offsetDateTime1.getMonthValue());
// Date of current time: 15
System.out.println(offsetDateTime1.getDayOfMonth());
// Current time: 13
System.out.println(offsetDateTime1.getHour());
// The current time is 14 minutes
System.out.println(offsetDateTime1.getMinute());
// The current time in seconds: 20
System.out.println(offsetDateTime1.getSecond());
Copy the code
Modify the year, month, day, hour, minute, second
LocalDateTime localDateTime1 = LocalDateTime.of(2021.8.15.13.14.20);
OffsetDateTime offsetDateTime1 = OffsetDateTime.of(localDateTime1, ZoneOffset.ofHours(8));
// Modify time year: 2022-08-15T13:14:20+08:00
System.out.println(offsetDateTime1.withYear(2022));
// Modify time month: 2021-09-15T13:14:20+08:00
System.out.println(offsetDateTime1.withMonth(9));
// Date of modification: 2021-08-30T13:14:20+08:00
System.out.println(offsetDateTime1.withDayOfMonth(30));
// Modify time: 2021-08-15T00:14:20+08:00
System.out.println(offsetDateTime1.withHour(0));
// Modify time: 2021-08-15T13:30:20+08:00
System.out.println(offsetDateTime1.withMinute(30));
// Modify time in seconds: 2021-08-15T13:14:59+08:00
System.out.println(offsetDateTime1.withSecond(59));
Copy the code
Compare date and time
LocalDateTime localDateTime1 = LocalDateTime.of(2021.8.15.13.14.20);
OffsetDateTime offsetDateTime1 = OffsetDateTime.of(localDateTime1, ZoneOffset.ofHours(8));
OffsetDateTime offsetDateTime3 = OffsetDateTime.of(localDateTime1, ZoneOffset.ofHours(8));
LocalDateTime localDateTime2 = LocalDateTime.of(2021.8.15.13.14.30);
OffsetDateTime offsetDateTime2 = OffsetDateTime.of(localDateTime2, ZoneOffset.ofHours(8));
// Return 0:-1; // Return 0:-1
System.out.println(offsetDateTime1.compareTo(offsetDateTime2));
// Compares whether the specified time is earlier than the parameter time (true is earlier) :true
System.out.println(offsetDateTime1.isBefore(offsetDateTime2));
// Compares whether the specified time is later than the parameter time (true is later) :false
System.out.println(offsetDateTime1.isAfter(offsetDateTime2));
// Compare whether two times are equal :true
System.out.println(offsetDateTime1.equals(offsetDateTime3));
Copy the code
The string is converted to an OffsetDateTime object
String str = "2021-08-15T10:15:30+08:00";
OffsetDateTime offsetDateTime1 = OffsetDateTime.parse(str);
OffsetDateTime offsetDateTime2 = OffsetDateTime.parse(str,DateTimeFormatter.ISO_OFFSET_DATE_TIME);
System.out.println(offsetDateTime1);
System.out.println(offsetDateTime2);
Copy the code
OffsetTime
OffsetTime class description
OffsetTime: Indicates the time with time offset
public final class OffsetTime
implements Temporal.TemporalAdjuster.Comparable<OffsetTime>, Serializable {
//The minimum supported {@code OffsetTime}, '00:00:00+18:00'.
public static final OffsetTime MIN = LocalTime.MIN.atOffset(ZoneOffset.MAX);
//The maximum supported {@code OffsetTime}, '23:59:59.9999999-18:00 '.
public static finalOffsetTime MAX = LocalTime.MAX.atOffset(ZoneOffset.MIN); . }Copy the code
MIN and MAX above are public static variables.
OffsetTime Common usage
Get the current time
OffsetTime offsetTime1 = OffsetTime.now();
OffsetTime offsetTime2 = OffsetTime.now(ZoneId.of("Asia/Shanghai"));
OffsetTime offsetTime3 = OffsetTime.now(Clock.systemUTC());
System.out.println("now :"+offsetTime1);
System.out.println("now by zone :"+offsetTime2);
System.out.println("now by Clock:"+offsetTime3);
Copy the code
Gets the OffsetTime object
LocalTime localTime1 = LocalTime.of(13.14.20);
OffsetTime offsetTime1 = OffsetTime.of(localTime1, ZoneOffset.ofHours(8));
OffsetTime offsetTime2 = OffsetTime. of(13.14.20.0, ZoneOffset.ofHours(8));
Instant now = Instant.now();
OffsetTime offsetTime3 = OffsetTime.ofInstant(now, ZoneId.of("Asia/Shanghai"));
System.out.println(offsetTime1);
System.out.println(offsetTime2);
System.out.println(offsetTime3);
Copy the code
Gets the hour and second of the specified time
LocalTime localTime1 = LocalTime.of( 13.14.20);
OffsetTime offsetTime1 = OffsetTime.of(localTime1, ZoneOffset.ofHours(8));
// Current time: 13
System.out.println(offsetTime1.getHour());
// The current time is 14 minutes
System.out.println(offsetTime1.getMinute());
// The current time in seconds: 20
System.out.println(offsetTime1.getSecond());
Copy the code
Change time minute second
LocalTime localTime1 = LocalTime.of( 13.14.20);
OffsetTime offsetTime1 = OffsetTime.of(localTime1, ZoneOffset.ofHours(8));
// Change time: 00:14:20+08:00
System.out.println(offsetTime1.withHour(0));
// Change the time of the minute: 13:30:20+08:00
System.out.println(offsetTime1.withMinute(30));
// Change the time in seconds: 13:14:59+08:00
System.out.println(offsetTime1.withSecond(59));
Copy the code
More time
LocalTime localTime1 = LocalTime.of( 13.14.20);
OffsetTime offsetTime1 = OffsetTime.of(localTime1, ZoneOffset.ofHours(8));
OffsetTime offsetTime3 = OffsetTime.of(localTime1, ZoneOffset.ofHours(8));
LocalTime localTime2 = LocalTime.of(13.14.30);
OffsetTime offsetTime2 = OffsetTime.of(localTime2, ZoneOffset.ofHours(8));
// Return 0:-1; // Return 0:-1
System.out.println(offsetTime1.compareTo(offsetTime2));
// Compares whether the specified time is earlier than the parameter time (true is earlier) :true
System.out.println(offsetTime1.isBefore(offsetTime2));
// Compares whether the specified time is later than the parameter time (true is later) :false
System.out.println(offsetTime1.isAfter(offsetTime2));
// Compare whether two times are equal :true
System.out.println(offsetTime1.equals(offsetTime3));
Copy the code
ZonedDateTime
ZonedDateTime class description
Represents a date and time with a time zone. ZonedDateTime can be interpreted as LocalDateTime+ZoneId
ZonedDateTime class defines LocalDateTime and ZoneId variables.
The ZonedDateTime class is also immutable and thread-safe.
public final class ZonedDateTime
implements Temporal.ChronoZonedDateTime<LocalDate>, Serializable {
/** * Serialization version. */
private static final long serialVersionUID = -6260982410461394882L;
/** * The local date-time. */
private final LocalDateTime dateTime;
/** * The time-zone. */
private finalZoneId zone; . }Copy the code
ZonedDateTime Common usage
Gets the current date and time
// Default time zone Obtains the current time
ZonedDateTime zonedDateTime = ZonedDateTime.now();
// Obtain the current time with the specified time zone. Asia/Shanghai is the Shanghai time zone
ZonedDateTime zonedDateTime1 = ZonedDateTime.now(ZoneId.of("Asia/Shanghai"));
//withZoneSameInstant is the conversion time zone. The parameter is ZoneId
ZonedDateTime zonedDateTime2 = zonedDateTime.withZoneSameInstant(ZoneId.of("America/New_York"));
System.out.println(zonedDateTime);
System.out.println(zonedDateTime1);
System.out.println(zonedDateTime2);
Copy the code
ZonedDateTime zonedDateTime1 = ZonedDateTime.now();
ZonedDateTime zonedDateTime2 = ZonedDateTime.now(ZoneId.of("Asia/Shanghai"));
ZonedDateTime zonedDateTime3 = ZonedDateTime.now(Clock.systemUTC());
System.out.println("now :"+zonedDateTime1);
System.out.println("now by zone :"+zonedDateTime2);
System.out.println("now by Clock:"+zonedDateTime3);
Copy the code
Get the ZonedDateTime object
LocalDateTime localDateTime1 = LocalDateTime.of(2021.8.15.13.14.20);
ZonedDateTime zonedDateTime1 = ZonedDateTime.of(localDateTime1, ZoneOffset.ofHours(8));
ZonedDateTime zonedDateTime2 = ZonedDateTime. of(2021.8.15.13.14.20.0, ZoneOffset.ofHours(8));
Instant now = Instant.now();
ZonedDateTime zonedDateTime3 = ZonedDateTime.ofInstant(now, ZoneId.of("Asia/Shanghai"));
System.out.println(zonedDateTime1);
System.out.println(zonedDateTime2);
System.out.println(zonedDateTime3);
Copy the code
Gets the year, month, day, hour, minute, second of the specified date
LocalDateTime localDateTime1 = LocalDateTime.of(2021.8.15.13.14.20);
ZonedDateTime zonedDateTime1 = ZonedDateTime.of(localDateTime1, ZoneOffset.ofHours(8));
// Current year: 2021
System.out.println(zonedDateTime1.getYear());
// Month of the current time: 8
System.out.println(zonedDateTime1.getMonthValue());
// Date of current time: 15
System.out.println(zonedDateTime1.getDayOfMonth());
// Current time: 13
System.out.println(zonedDateTime1.getHour());
// The current time is 14 minutes
System.out.println(zonedDateTime1.getMinute());
// The current time in seconds: 20
System.out.println(zonedDateTime1.getSecond());
Copy the code
Modify the year, month, day, hour, minute, second
LocalDateTime localDateTime1 = LocalDateTime.of(2021.8.15.13.14.20);
ZonedDateTime zonedDateTime1 = ZonedDateTime.of(localDateTime1, ZoneOffset.ofHours(8));
// Modify time year: 2022-08-15T13:14:20+08:00
System.out.println(zonedDateTime1.withYear(2022));
// Modify time month: 2021-09-15T13:14:20+08:00
System.out.println(zonedDateTime1.withMonth(9));
// Date of modification: 2021-08-30T13:14:20+08:00
System.out.println(zonedDateTime1.withDayOfMonth(30));
// Modify time: 2021-08-15T00:14:20+08:00
System.out.println(zonedDateTime1.withHour(0));
// Modify time: 2021-08-15T13:30:20+08:00
System.out.println(zonedDateTime1.withMinute(30));
// Modify time in seconds: 2021-08-15T13:14:59+08:00
System.out.println(zonedDateTime1.withSecond(59));
Copy the code
Compare date and time
LocalDateTime localDateTime1 = LocalDateTime.of(2021.8.15.13.14.20);
ZonedDateTime zonedDateTime1 = ZonedDateTime.of(localDateTime1, ZoneOffset.ofHours(8));
ZonedDateTime zonedDateTime3 = ZonedDateTime.of(localDateTime1, ZoneOffset.ofHours(8));
LocalDateTime localDateTime2 = LocalDateTime.of(2021.8.15.13.14.30);
ZonedDateTime zonedDateTime2 = ZonedDateTime.of(localDateTime2, ZoneOffset.ofHours(8));
// Return 0:-1; // Return 0:-1
System.out.println(zonedDateTime1.compareTo(zonedDateTime2));
// Compares whether the specified time is earlier than the parameter time (true is earlier) :true
System.out.println(zonedDateTime1.isBefore(zonedDateTime2));
// Compares whether the specified time is later than the parameter time (true is later) :false
System.out.println(zonedDateTime1.isAfter(zonedDateTime2));
// Compare whether two times are equal :true
System.out.println(zonedDateTime1.equals(zonedDateTime3));
Copy the code
LocalDateTime + ZoneId ZonedDateTime
LocalDateTime localDateTime = LocalDateTime.now();
ZonedDateTime zonedDateTime1 = localDateTime.atZone(ZoneId.systemDefault());
ZonedDateTime zonedDateTime2 = localDateTime.atZone(ZoneId.of("America/New_York"));
System.out.println(zonedDateTime1);
System.out.println(zonedDateTime2);
Copy the code
The above example shows that LocalDateTime can be converted to ZonedDateTime.
Recommend related articles
Hutool date and time series articles
1DateUtil(Time utility class)- current time and current timestamp
2DateUtil(Time tool Class)- Common time types Date, DateTime, Calendar and TemporalAccessor (LocalDateTime) conversions
3DateUtil(Time utility class)- Get various contents for dates
4DateUtil(Time utility class)- Format time
5DateUtil(Time utility class)- Parse the time being formatted
6DateUtil(Time utility class)- Time offset gets
7DateUtil(Time utility class)- Date calculation
8ChineseDate(Lunar Date tools)
9LocalDateTimeUtil({@link LocalDateTime} utility class encapsulation in JDK8+)
10TemporalAccessorUtil{@link TemporalAccessor} Tool class encapsulation
other
To explore the underlying source code at the core of the JDK, you must master native usage
Swastika blog teaches you to understand Java source code date and time related usage
Java’s SimpleDateFormat thread is unsafe
Source code analysis: JDK risks and best practices for getting default time zones