[new features of JDK8] Date/Time API(JSR 310)

Posted by 1337hovie on Mon, 21 Feb 2022 13:31:50 +0100

 
May you be like sunshine, bright and not sad.

Links [programming protocol] date and time

 

1. Date and time API overview

Date/Time API Java 8 further strengthens the processing of date and time by publishing a new date time API (JSR 310). Improved many problems in the date time API in the old version of Java, including:

  • Non thread safe: − Java util. Date is non thread safe, and all date classes are variable, which is one of the biggest problems of Java date classes.
  • Troublesome time zone processing: the date class does not provide internationalization and does not have time zone support, so Java has introduced Java util. Calendar and Java util. All of the above timezone classes have the same problem.

java. There are many classes in the time package that can represent time and date. This is a very rich API.


 

  • Description and function of class
    Date and time are distinguished. The unit of date is month, year and day. The unit of time is hour, minute and second.
methodexplain
ClockClock class, including time zone information
DateTimeExceptionException, used to indicate problems in calculating date and time
DayOfWeekEnumeration class, 7 days of the week
DurationThe difference between two times, accurate to seconds or nanoseconds
InstantTimestamp (instantaneous time with time zone)
LocalDateDate (e.g. February 18, 2022, without time zone)
LocalDateTimeDate and time (e.g. 2022-02-18 17:03:10, without time zone)
LocalTimeTime (e.g. 17:03:10, without time zone)
Monthmonth
MonthDayMonth day
OffsetDateTimeDate and time with offset (for example: 2022-02-18T17:03:10+01:00)
OffsetTimeTime with offset (for example: 17:03:10 + 01:00)
PeroidDifference between two dates (accurate to day)
SerShared serialization delegate for this package
Yearyear
YearMonthyears
ZonedDateTimeDate time with time zone
ZonedIdtime zone
ZoneOffsetTime zone offset (for example: + 8:00)
ZoneRegionGeographical area to which the same time zone rule applies

 

2. Clock.class

  • Method example
    A clock that provides access to the current instant, date, and time using a time zone instead of system Currenttimemillis() and timezone getDefault(). It is an abstract class with four subclasses.
methodexplain
SystemClockImplement a clock that always returns the latest time
FixedClockThe realization that a clock always returns the same moment is usually used for testing
OffsetClockImplementation of clock adding offset to basic clock
TickClockImplementation of clock adding offset to basic clock
systemUTCClock converted to date and time using UTC time zone
systemDefaultZoneClock converted to date and time using default time zone
systemUse the clock of the best available system clock in the specified area
tickMillisA clock whose time is in milliseconds
tickSecondsA clock in seconds
tickMinutesA clock in minutes
tickReturns a clock constructed based on the basic clock and the basic unit of clock recording, such as a half second clock
fixedOnly the clock of the specified instant is returned to ensure that the test does not depend on the current clock
offsetReturns the clock to which the offset is added to the base clock
getZoneGets the time zone used
withZoneReturns the clock with the specified time zone based on this clock
millisGets the current millisecond instant of the clock
instantGet timestamp (current time)
*****************************************************************
public class TestDateTime {
    public static void main(String[] args) {
        // Clock using UTC time zone
        Clock clockSystemUTC = Clock.systemUTC();
        System.out.println("clockSystemUTC\t\t" + clockSystemUTC.instant());
        // Use the clock of the system default time zone
        Clock clockSystemDefaultZone = Clock.systemDefaultZone();
        System.out.println("clockSystemDefaultZone\t\t" + clockSystemDefaultZone.instant());
        // Use the Phoenix time zone clock
        Clock clockSystem = Clock.system(ZoneId.of("America/Phoenix"));
        System.out.println("clockSystem\t\t" + clockSystem.instant());
        // Use short time zone name (not recommended) CTT - Asia/Shanghai clock in milliseconds
        Clock clockTickMillis = Clock.tickMillis(ZoneId.of(ZoneId.SHORT_IDS.get("CTT")));
        System.out.println("clockTickMillis\t\t" + clockTickMillis.instant());
        // Clock in seconds
        Clock clockTickSeconds = Clock.tickSeconds(ZoneId.of("Asia/Shanghai"));
        System.out.println("clockTickSeconds\t\t" + clockTickSeconds.instant());
        // Clock in minutes
        Clock clockTickMinutes = Clock.tickMinutes(ZoneId.of("Asia/Shanghai"));
        System.out.println("clockTickMinutes\t\t" + clockTickMinutes.instant());
        // A clock in two days
        Clock clockTick = Clock.tick(clockSystemUTC, Duration.ofDays(2));
        System.out.println("clockTick\t\t" + clockTick.instant());
        // Fixed clock
        Clock clockFixed = Clock.fixed(clockSystemUTC.instant(), ZoneId.of("Asia/Shanghai"));
        System.out.println("clockFixed\t\t" + clockFixed.instant());
        // Clock offset by seven days
        Clock clockOffset = Clock.offset(clockSystemUTC, Duration.ofDays(7));
        System.out.println("clockOffset\t\t" + clockOffset.instant());
        // Gets the time zone of the clock
        ZoneId zoneId = clockSystemUTC.getZone();
        System.out.println("zoneId\t\t" + zoneId.getId());
        // Get a copy of the clock with Asia Shanghai time zone
        Clock clockWithZone = clockSystemUTC.withZone(ZoneId.of("Asia/Shanghai"));
        System.out.println("clockWithZone\t\t" + clockWithZone.instant());
        // Gets the current millisecond instant of the clock
        long millis = clockSystemUTC.millis();
        System.out.println("millis\t\t" + millis);
    }
}
[Console]-------------------------------------------------------
clockSystemUTC				2022-02-21T11:21:11.451353700Z
clockSystemDefaultZone		2022-02-21T11:21:11.510197500Z
clockSystem					2022-02-21T11:21:11.511194300Z
clockTickMillis				2022-02-21T11:21:11.512Z
clockTickSeconds			2022-02-21T11:21:11Z
clockTickMinutes			2022-02-21T11:21:00Z
clockTick					2022-02-21T00:00:00Z
clockFixed					2022-02-21T11:21:11.514185900Z
clockOffset					2022-02-28T11:21:11.514185900Z
zoneId						Z
clockWithZone				2022-02-21T11:21:11.516180600Z
millis						1645442471516
*****************************************************************

 

3. LocalDateTime.class

  • Method example
    The ISO-8601 calendar system has no date and time in the time zone, for example, 2007-12-03T10:15:30. This class is immutable and thread safe.
methodexplain
nowGets the current date and time from the system clock in the default time zone
ofGets an instance of LocalDateTime from year, month, day, hour, and minute
ofInstantGet an instance of LocalDateTime from Instant and ZoneId
ofEpochSecondUse the seconds of 1970-01-01T00:00:00Z era to obtain an instance of LocalDateTime
fromGets an instance of LocalDateTime from the time object
parseGet an instance of LocalDateTime from text strings such as 2007-12-03T10:15:30
isSupportedCheck whether this date and time can be queried for the specified field
rangeGets the range of valid values for the specified field
getGets the value of the specified field as int from this date time
getLongGets the value of the specified field as long from this date and time
toLocalDateGets the LocalDate part of this date time
toLocalTimeGets the LocalTime part of this date time
getYearGet year field
getMonthValueGets the year field from 1 to 12
getMonthUse the Month enumeration to get the Month field
getDayOfMonthGet the day of the month
getDayOfYearGet the day of the year
getDayOfWeekGets the week field, which is an enumeration DayOfWeek
getHourGet hours
getMinuteGet minutes
getSecondGet seconds
getNanoGet nanoseconds
withReturns an adjusted copy of this date and time
truncatedToReturns a copy of this LocalDateTime, where the time is truncated
plusReturns a copy of this date and time with the specified number added
minusReturns a copy of this date and time minus the specified amount
queryQuery this date and time using the specified query
adjustIntoAdjusts the specified time object to have the same date and time as the object
untilCalculates the amount of time up to another date and time in specified units
formatFormat this date and time using the specified formatter
atZoneCombine this date time with the time zone to create ZonedDateTime
atOffsetCombine this datetime with an offset to create an OffsetDateTime
compareToCompare this date time with another date time
isAfterCheck whether this date and time is after the specified date and time
isBeforeCheck whether this date and time is before the specified date and time
isEqualCheck whether this date and time are equal to the specified date and time
*****************************************************************
public class TestDateTime {
    public static void main(String[] args) {
        // Get current local time
        LocalDateTime nowLocalDateTime = LocalDateTime.now();
        System.out.println("nowLocalDateTime\t\t" + nowLocalDateTime);
        // User defined month, day, hour, minute and second
        LocalDateTime ofLocalDateTime = LocalDateTime.of(2022, 3, 21, 14, 00, 00);
        System.out.println("ofLocalDateTime\t\t" + ofLocalDateTime);
        // Add time zone from current time
        LocalDateTime ofInstantLocalDateTime = LocalDateTime.ofInstant(LocalDateTime.now().toInstant(ZoneOffset.UTC), ZoneId.of("America/Chicago"));
        System.out.println("ofInstantLocalDateTime\t\t" + ofInstantLocalDateTime);
        // From 1970-01-01T00:00:00Z era, 100000 era seconds and 1000 nanoseconds of coordinated universal time
        LocalDateTime ofEpochSecondLocalDateTime = LocalDateTime.ofEpochSecond(100000, 1000, ZoneOffset.UTC);
        System.out.println("ofEpochSecondLocalDateTime\t\t" + ofEpochSecondLocalDateTime);
        // Gets an instance of LocalDateTime from the time object
        LocalDateTime fromLocalDateTime = LocalDateTime.from(ZonedDateTime.now());
        System.out.println("fromLocalDateTime\t\t" + fromLocalDateTime);
        // Parse text string
        LocalDateTime parseLocalDateTime = LocalDateTime.parse("2018-12-30T12:00:00.00");
        System.out.println("parseLocalDateTime\t\t" + parseLocalDateTime);
        // Check whether it can be DAY_OF_WEEK queries this date and time
        Boolean isSupportedLocalDateTime = parseLocalDateTime.isSupported(ChronoField.DAY_OF_WEEK);
        System.out.println("isSupportedLocalDateTime\t\t" + isSupportedLocalDateTime);
        // DAY_ OF_ Scope of month
        ValueRange range = nowLocalDateTime.range(ChronoField.DAY_OF_MONTH);
        System.out.println("range\t\t" + range);
        // Gets that the current date is the first day of the year
        int getLocalDateTime = nowLocalDateTime.get(ChronoField.DAY_OF_YEAR);
        System.out.println("getLocalDateTime\t\t" + getLocalDateTime);
        // Adjust the current date to the end of the month
        LocalDateTime withLocalDateTime = nowLocalDateTime.with(TemporalAdjusters.lastDayOfMonth());
        System.out.println("withLocalDateTime\t\t" + withLocalDateTime);
        // Truncation date to days
        LocalDateTime truncatedToLocalDateTime = nowLocalDateTime.truncatedTo(ChronoUnit.DAYS);
        System.out.println("truncatedToLocalDateTime\t\t" + truncatedToLocalDateTime);
        // Add ten days to the current date
        LocalDateTime plusLocalDateTime = nowLocalDateTime.plus(Period.ofDays(10));
        System.out.println("plusLocalDateTime\t\t" + plusLocalDateTime);
        // Current date minus ten days
        LocalDateTime minusLocalDateTime = nowLocalDateTime.minus(Period.ofDays(10));
        System.out.println("minusLocalDateTime\t\t" + minusLocalDateTime);
        // Query whether the current date and time includes local date
        LocalDate query = nowLocalDateTime.query(TemporalQueries.localDate());
        System.out.println("query\t\t" + query);
        // Adjust the current date to Wednesday
        Temporal adjustIntoLocalDateTime = DayOfWeek.WEDNESDAY.adjustInto(nowLocalDateTime);
        System.out.println("adjustIntoLocalDateTime\t\t" + adjustIntoLocalDateTime);
        // Gets the number of days from the current date to the specified date
        long until = nowLocalDateTime.until(ofLocalDateTime, ChronoUnit.DAYS);
        System.out.println("until\t\t" + until);
        // format date
        DateTimeFormatter formatter = DateTimeFormatter.ISO_DATE;
        String formatLocalDateTime = nowLocalDateTime.format(formatter);
        System.out.println("formatLocalDateTime\t\t" + formatLocalDateTime);
        // Create an offset of two hours
        OffsetDateTime atOffsetLocalDateTime = nowLocalDateTime.atOffset(ZoneOffset.ofHours(2));
        System.out.println("atOffsetLocalDateTime\t\t" + atOffsetLocalDateTime);
        // Time when the Chicago time zone was created
        ZonedDateTime atZoneLocalDateTime = nowLocalDateTime.atZone(ZoneId.of("America/Chicago"));
        System.out.println("atZoneLocalDateTime\t\t" + atZoneLocalDateTime);
        // Compare two times
        int compareToLocalDateTime = withLocalDateTime.compareTo(nowLocalDateTime);
        System.out.println("compareToLocalDateTime\t\t" + compareToLocalDateTime);
    }
}

[Console]-------------------------------------------------------
nowLocalDateTime				2022-02-21T17:54:48.973290700
ofLocalDateTime					2022-03-21T14:00
ofInstantLocalDateTime			2022-02-21T11:54:48.996229200
ofEpochSecondLocalDateTime		1970-01-02T03:46:40.000001
fromLocalDateTime				2022-02-21T17:54:49.001215600
parseLocalDateTime				2018-12-30T12:00
isSupportedLocalDateTime		true
range							1 - 28
getLocalDateTime				52
withLocalDateTime				2022-02-28T17:54:48.973290700
truncatedToLocalDateTime		2022-02-21T00:00
plusLocalDateTime				2022-03-03T17:54:48.973290700
minusLocalDateTime				2022-02-11T17:54:48.973290700
query							2022-02-21
adjustIntoLocalDateTime			2022-02-23T17:54:48.973290700
until							27
formatLocalDateTime				2022-02-21
atOffsetLocalDateTime			2022-02-21T17:54:48.973290700+02:00
atZoneLocalDateTime				2022-02-21T17:54:48.973290700-06:00[America/Chicago]
compareToLocalDateTime			7
*****************************************************************

 

4. ChronoField.class

  • Tool class description
    Inherit TemporalField and enumerate classes. Similar to the chrononunit function, it is implemented based on TemporalUnit and is generally used to obtain values in different time domains.
*****************************************************************
public enum ChronoField implements TemporalField {
    NANO_OF_SECOND("NanoOfSecond", NANOS, SECONDS, ValueRange.of(0, 999_999_999)),
    NANO_OF_DAY("NanoOfDay", NANOS, DAYS, ValueRange.of(0, 86400L * 1000_000_000L - 1)),
    MICRO_OF_SECOND("MicroOfSecond", MICROS, SECONDS, ValueRange.of(0, 999_999)),
    MICRO_OF_DAY("MicroOfDay", MICROS, DAYS, ValueRange.of(0, 86400L * 1000_000L - 1)),
    MILLI_OF_SECOND("MilliOfSecond", MILLIS, SECONDS, ValueRange.of(0, 999)),
    MILLI_OF_DAY("MilliOfDay", MILLIS, DAYS, ValueRange.of(0, 86400L * 1000L - 1)),
    SECOND_OF_MINUTE("SecondOfMinute", SECONDS, MINUTES, ValueRange.of(0, 59), "second"),
    SECOND_OF_DAY("SecondOfDay", SECONDS, DAYS, ValueRange.of(0, 86400L - 1)),
    MINUTE_OF_HOUR("MinuteOfHour", MINUTES, HOURS, ValueRange.of(0, 59), "minute"),
    MINUTE_OF_DAY("MinuteOfDay", MINUTES, DAYS, ValueRange.of(0, (24 * 60) - 1)),
    HOUR_OF_AMPM("HourOfAmPm", HOURS, HALF_DAYS, ValueRange.of(0, 11)),
    CLOCK_HOUR_OF_AMPM("ClockHourOfAmPm", HOURS, HALF_DAYS, ValueRange.of(1, 12)),
    HOUR_OF_DAY("HourOfDay", HOURS, DAYS, ValueRange.of(0, 23), "hour"),
    CLOCK_HOUR_OF_DAY("ClockHourOfDay", HOURS, DAYS, ValueRange.of(1, 24)),
    AMPM_OF_DAY("AmPmOfDay", HALF_DAYS, DAYS, ValueRange.of(0, 1), "dayperiod"),
    DAY_OF_WEEK("DayOfWeek", DAYS, WEEKS, ValueRange.of(1, 7), "weekday"),
    ALIGNED_DAY_OF_WEEK_IN_MONTH("AlignedDayOfWeekInMonth", DAYS, WEEKS, ValueRange.of(1, 7)),
    ALIGNED_DAY_OF_WEEK_IN_YEAR("AlignedDayOfWeekInYear", DAYS, WEEKS, ValueRange.of(1, 7)),
    DAY_OF_MONTH("DayOfMonth", DAYS, MONTHS, ValueRange.of(1, 28, 31), "day"),
    DAY_OF_YEAR("DayOfYear", DAYS, YEARS, ValueRange.of(1, 365, 366)),
    EPOCH_DAY("EpochDay", DAYS, FOREVER, ValueRange.of(-365243219162L, 365241780471L)),
    ALIGNED_WEEK_OF_MONTH("AlignedWeekOfMonth", WEEKS, MONTHS, ValueRange.of(1, 4, 5)),
    ALIGNED_WEEK_OF_YEAR("AlignedWeekOfYear", WEEKS, YEARS, ValueRange.of(1, 53)),
    MONTH_OF_YEAR("MonthOfYear", MONTHS, YEARS, ValueRange.of(1, 12), "month"),
    PROLEPTIC_MONTH("ProlepticMonth", MONTHS, FOREVER, ValueRange.of(Year.MIN_VALUE * 12L, Year.MAX_VALUE * 12L + 11)),
    YEAR_OF_ERA("YearOfEra", YEARS, FOREVER, ValueRange.of(1, Year.MAX_VALUE, Year.MAX_VALUE + 1)),
    YEAR("Year", YEARS, FOREVER, ValueRange.of(Year.MIN_VALUE, Year.MAX_VALUE), "year"),
    ERA("Era", ERAS, FOREVER, ValueRange.of(0, 1), "era"),
    INSTANT_SECONDS("InstantSeconds", SECONDS, FOREVER, ValueRange.of(Long.MIN_VALUE, Long.MAX_VALUE)),
    OFFSET_SECONDS("OffsetSeconds", SECONDS, FOREVER, ValueRange.of(-18 * 3600, 18 * 3600));
    
    private final String name;
    private final TemporalUnit baseUnit;
    private final TemporalUnit rangeUnit;
    private final ValueRange range;
    private final String displayNameKey;

    private ChronoField(String name, TemporalUnit baseUnit, TemporalUnit rangeUnit, ValueRange range) {
        this.name = name;
        this.baseUnit = baseUnit;
        this.rangeUnit = rangeUnit;
        this.range = range;
        this.displayNameKey = null;
    }

    private ChronoField(String name, TemporalUnit baseUnit, TemporalUnit rangeUnit,
            ValueRange range, String displayNameKey) {
        this.name = name;
        this.baseUnit = baseUnit;
        this.rangeUnit = rangeUnit;
        this.range = range;
        this.displayNameKey = displayNameKey;
    }
}
*****************************************************************

 

5. ChronoUnit.class

  • Tool class description
    Time measurement unit, enumeration class, inheriting TemporalUnit. It indicates the unit used to measure a time interval. For example, the time interval between two days can be expressed by 48 hours instead. It is generally used for the setting of a certain time unit and the operation of addition and subtraction.
*****************************************************************
public enum ChronoUnit implements TemporalUnit {
    NANOS("Nanos", Duration.ofNanos(1)),
    MICROS("Micros", Duration.ofNanos(1000)),
    MILLIS("Millis", Duration.ofNanos(1000_000)),
    SECONDS("Seconds", Duration.ofSeconds(1)),
    MINUTES("Minutes", Duration.ofSeconds(60)),
    HOURS("Hours", Duration.ofSeconds(3600)),
    HALF_DAYS("HalfDays", Duration.ofSeconds(43200)),
    DAYS("Days", Duration.ofSeconds(86400)),
    WEEKS("Weeks", Duration.ofSeconds(7 * 86400L)),
    MONTHS("Months", Duration.ofSeconds(31556952L / 12)),
    YEARS("Years", Duration.ofSeconds(31556952L)),
    DECADES("Decades", Duration.ofSeconds(31556952L * 10L)),
    CENTURIES("Centuries", Duration.ofSeconds(31556952L * 100L)),
    MILLENNIA("Millennia", Duration.ofSeconds(31556952L * 1000L)),
    ERAS("Eras", Duration.ofSeconds(31556952L * 1000_000_000L)),
    FOREVER("Forever", Duration.ofSeconds(Long.MAX_VALUE, 999_999_999));

    private final String name;
    private final Duration duration;

    private ChronoUnit(String name, Duration estimatedDuration) {
        this.name = name;
        this.duration = estimatedDuration;
    }
}
*****************************************************************

 

6. TemporalAdjuster.class

  • Tool class description
    Because Java The time classes of time are immutable, so you can call this method when you need to adjust the time. jdk provides some tool classes for default adjustment methods, TemporalAdjusters.
*****************************************************************
public final class TemporalAdjusters {
	// Set the day unit measurement to the first day of the year
	public static TemporalAdjuster firstDayOfYear()
	// Set the day unit measurement to the last day of the year
	public static TemporalAdjuster lastDayOfYear()
	// Set the time to the first day of the next year
	public static TemporalAdjuster firstDayOfNextYear() 
	// Set the time to the first day of the month
	public static TemporalAdjuster firstInMonth(DayOfWeek dayOfWeek)
	// Set the time to the last day of the month
	public static TemporalAdjuster lastInMonth(DayOfWeek dayOfWeek)
	// Set the time to the day of the week in the ordinal week of the current month - dayOfWeek
	public static TemporalAdjuster dayOfWeekInMonth(int ordinal, DayOfWeek dayOfWeek)
	// Set the time to the day of next week
	public static TemporalAdjuster next(DayOfWeek dayOfWeek) 
	// Set the time to the day of last week
	public static TemporalAdjuster previous(DayOfWeek dayOfWeek)
	// If the current week is different from dayOfWeek, set the time to the day of last week - dayOfWeek
	public static TemporalAdjuster previousOrSame(DayOfWeek dayOfWeek)
}
*****************************************************************

There are many not listed here, tired

Topics: Java Back-end