preface

We’ve been using Date, Calender, and SimpleDateFormat before jdK8, but it’s been criticized for its weak API and thread-safety issues. The java.time class is immutable and thread-safe. It was implemented by the same author as Joda, so it takes a lot of features from Joda. If you are used to Joda, you can easily switch to the Java.time class

Pay attention to the public account, communicate together, wechat search: sneak forward

A brief introduction to the java.time class

  • The unit of Date is year, month and day. The unit of time is minutes and seconds
class describe
Instant Timestamp (instantaneous time, with time zone)
LocalDate Date (e.g. : 2018-09-24, without time zone)
LocalTime Time (e.g. 10:32:10, no time zone)
LocalDateTime Date and time (e.g. 2018-09-24 10:32:10, without time zone)
Duration The difference between two times, accurate to the second or nanosecond
Peroid Difference between two dates (exact to the day)
DateTimeFormatter Date-time formatting class
ZoneId The time zone
ZoneOffset Time zone offset (for example, +8:00)
ZonedDateTime Date time with time zone
ChronoUnit Date enumeration class (available in time addition and subtraction operations to)
MonthDay On the day
YearMonth years

Clock Clock

  • Clock is the Clock associated with the TimeZone. Clock can get the timestamp and TimeZone ZoneId instead of system.currenttimemillis () and timezone.getdefault (). It’s an abstract class with four subclasses

public static Clock systemDefaultZone(a)
public static Clock offset(Clock baseClock, Duration offsetDuration)
public static Clock tick(Clock baseClock, Duration tickDuration)
public static Clock fixed(Instant fixedInstant, ZoneId zone)-------- The following methods are implemented by the above four subclasses ---------// Get the time zone
public abstract ZoneId getZone(a)
// Specify the time zone
public abstract Clock withZone(ZoneId zone)
// Get the timestamp
public abstract Instant instant(a)
Copy the code
  • The default local clock is SystemClock
Clock clock = Clock.systemDefaultZone(); System.out.println(clock.getZone()); Instant instant = clock.instant(); System.out.println(instant); ---------- Command output ----------- Asia/Shanghai2021-01-03T05:05:31.791Z
1609650331791
Copy the code
  • OffsetClock OffsetClock
Clock clock = Clock.systemDefaultZone();
Clock pastClock = Clock.offset(clock, Duration.ofMillis(-10000));
System.out.println(pastClock.getZone());
// The current pastClock is 10000 milliseconds different from the past pastClockSystem.out.println(clock.millis() - pastClock.millis()); ---------- The command output is -----------10000
Copy the code
  • TickDuration: TickDuration to the nearest last or next period. Note: TickDuration does not take the current point in time as the start time of the period
Clock clock = Clock.systemDefaultZone();
Clock nearestHourClock = Clock.tick(clock, Duration.ofMillis(10));
// The current time is 2021-01-03T05:36:54.088z, the period is 10 milliseconds, TickDuration is automatic
// Select 2021-01-03T05:36:54.090z as the start time
System.out.println(clock.instant());
System.out.println(nearestHourClock.instant());
Thread.sleep(10); System.out.println(clock.instant()); System.out.println(nearestHourClock.instant()); ---------- The command output is -----------2021-01-03T05:43:19.088Z
2021-01-03T05:43:19.090Z
2021-01-03T05:43:19.107Z
2021-01-03T05:43:19.100Z
Copy the code
  • Time-invariant FixedInstant
Clock clock = Clock.systemDefaultZone();
Clock fixedClock = Clock.fixed(clock.instant(), ZoneId.systemDefault());
System.out.println(fixedClock.instant());
Thread.sleep(1000); System.out.println(fixedClock.instant()); ---------- The command output is -----------2021-01-03T05:27:43.272Z
2021-01-03T05:27:43.272Z
Copy the code

Temporal

  • Time class unified interface, define some common method operations, such as: a unit of time plus or minus, set to a time domain to a fixed value
public interface Temporal extends TemporalAccessor {
    // Get the TemporalField range value that the time class can represent
    public ValueRange range(TemporalField field)
    // Set the value of the TemporalField time domain
    public Temporal with(TemporalField field, long newValue)
    // Convert time according to TemporalAdjuster interface
    public Temporal with(TemporalAdjuster adjuster)
    // Increase the number of designated TemporalUnit units
    public Temporal plus(long amountToAdd, TemporalUnit unit)
    // Reduce the number of designated TemporalUnit units
    public Temporal minus(long amountToSubtract, TemporalUnit unit)
Copy the code
  • A subclass of Temporal

Instant

  • Instant is used to manipulate timestamps, with time zones, Greenwich in UTC by default. Therefore, when other time classes communicate with Instant, you need to specify your own time zone
public static Instant now(a)
public static Instant now(Clock clock)
// Generate Instant in milliseconds
public static Instant ofEpochMilli(long epochMilli)
// Instant is generated in seconds, with a value in seconds
public static Instant ofEpochSecond(long epochSecond, long nanoAdjustment)
// Text format: 2021-01-04T06:37:53.743z
public static Instant parse(CharSequence text) 
// Calculate the time difference with Temporal, measured in TemporalUnit
public long until(Temporal endExclusive, TemporalUnit unit) 
Copy the code
  • Creation of the timestamp
Instant instant = Instant.now();
System.out.println(instant);
instant = Instant.now(Clock.systemDefaultZone());
System.out.println(instant);
// Convert to Date
instant = Instant.ofEpochMilli(new Date().getTime());
System.out.println(instant);
// Support up to nanosecond level depending on string generation time
instant = Instant.parse("The 1995-10-23 T10: treasure. 999999999 z");
System.out.println(instant);
// Create a timestamp in seconds and offset nanoseconds
Instant preInstant = Instant.ofEpochSecond(1609741558.1);
// The difference between the past time and the current time. TemporalUnit can be specifiedSystem.out.println(preInstant.until(Instant.now(), ChronoUnit.MINUTES)); --------------- The command output is ------------------------2021-01-04T06:37:53.743Z
2021-01-04T06:37:53.795Z
2021-01-04T06:37:53.795Z
1995-10-23T10:12:35.999999999Z
2021-01-04T06:25:58.000000001Z
2021-01-04T06:37:53.798Z
11
Copy the code
  • The use of Instant
Instant instant = Instant.now();
// Set the time zone to America/El_Salvador
ZonedDateTime zonedDateTime = instant.atZone(ZoneId.of("America/El_Salvador"));
System.out.println(zonedDateTime);
// Set the time zone to offset -6 (US)
OffsetDateTime offsetDateTime = instant.atOffset(ZoneOffset.ofHours(-6));
System.out.println(offsetDateTime);
// The number of days is increased by 2 and the number of minutes is decreased by 1. The number of months is set to December
Instant fixInstant = instant.minus(1, ChronoUnit.MINUTES)
        .plus(2, ChronoUnit.DAYS); System.out.println(instant); System.out.println(fixInstant); --------------- The command output is -----------------2021-01-04T00:53:01.895-06:00[America/El_Salvador]
2021-01-04T00:53:01.895-06:00
2021-01-04T06:53:01.895Z
2021-01-06T06:52:01.895Z
Copy the code

LocalTime

  • LocalTime is a class for manipulating minutes and seconds, plus nanosecond accuracy; There is no time zone concept. You need to set the time zone before transferring to Instant
  • Constructor of LocalTime
public static LocalTime now(a) 
public static LocalTime of(int hour, int minute, int second, int nanoOfSecond)
// The number of seconds since dawn
public static LocalTime ofSecondOfDay(long secondOfDay)
// The number of nanoseconds since dawn
public static LocalTime ofNanoOfDay(long nanoOfDay)
public static LocalTime parse(CharSequence text, DateTimeFormatter formatter) 
//jdk9
public static LocalTime ofInstant(Instant instant, ZoneId zone)
Copy the code
  • Conversion of LocalTime to other time classes
public LocalDateTime atDate(LocalDate date)
public OffsetTime atOffset(ZoneOffset offset) 
public long toEpochSecond(LocalDate date, ZoneOffset offset)
Copy the code
  • LocalTime create example
// 1 is in nanoseconds
LocalTime localTime = LocalTime.of(12.12.12.1);
System.out.println(localTime);
localTime = LocalTime.ofSecondOfDay(60 * 60 * 12 + 60 * 12);
System.out.println(localTime);
localTime = LocalTime.parse("12:12:12", DateTimeFormatter.ISO_TIME); System.out.println(localTime); --------------- The command output is -----------------12:12:12.000000001
12:12
12:12:12
Copy the code
  • Common handling of LocalTime
LocalTime localTime = LocalTime.of(12.12.12.1);
System.out.println(localTime);
// Concatenate dates to generate dates and times
LocalDateTime dateTime = localTime.atDate(LocalDate.now());
System.out.println(dateTime);
// Set the time zone
OffsetTime offsetTime = LocalTime.now().atOffset(ZoneOffset.ofHours(-6));
System.out.println(offsetTime);
// Add the current time and date, and set the time zone to offset
long seconds = LocalTime.now().toEpochSecond(LocalDate.now(), ZoneOffset.ofHours(-6)); System.out.println(seconds); --------------- The command output is -----------------12:12:12.000000001
2021-01-04T12:12:12.000000001
16:29:33.917387700-06:00
1609799373
Copy the code

LocalDate

  • LocalDate is the class used to manipulate the year, month and day; Units of time are as of the end of the day, excluding hours and subsequent units
public static LocalDate now(a)
public static LocalDate of(int year, int month, int dayOfMonth)
public static LocalDate ofInstant(Instant instant, ZoneId zone)
Copy the code
// It was the day of the month
public int getDayOfMonth(a)
// It was the day of the year
public int getDayOfYear(a)
// What is the day of the week (1-7)
public DayOfWeek getDayOfWeek(a) 
// Whether leap year
public boolean isLeapYear(a) 
public LocalDateTime atTime(LocalTime time)
// Set the time to early today
public LocalDateTime atStartOfDay(a)
The following two methods are jdk9, which fetch the current date to each date of endExclusive
public Stream<LocalDate> datesUntil(LocalDate endExclusive)
public Stream<LocalDate> datesUntil(LocalDate endExclusive, Period step) 
Copy the code
  • Example of creating LocalDate
LocalDate localDate = LocalDate.now();
System.out.println(localDate);
localDate = LocalDate.of(2020.3.19);
System.out.println(localDate);
localDate = LocalDate.parse("20210319", DateTimeFormatter.BASIC_ISO_DATE); System.out.println(localDate); --------------- The command output is -----------------2021-01-04
2020-03-19
2021-03-19
Copy the code
  • The operation of LocalDate
LocalDate localDate = LocalDate.parse("20210319", DateTimeFormatter.BASIC_ISO_DATE);
System.out.println("Day of the current year :" + localDate.getDayOfYear() + "; The day of the current month." + localDate.getDayOfMonth()+"; Current day of the week :"+localDate.getDayOfWeek());
// Add LocalTime to LocalDateTimeLocalDateTime dateTime = localDate.atTime(LocalTime.now()); System.out.println(dateTime); --------------- Command output ----------------- Day of the current year:78; The day of the month19; Current Day :FRIDAY2021-03-19T15:37:54.713
Copy the code

LocalDateTime

  • LocalDate and LocalTime, used to represent the year, month, day, hour, minute, second class, plus accurate to nanosecond level; There is no time zone concept. You need to set the time zone before transferring to Instant
public static LocalDateTime now(a)
public static LocalDateTime of(int year, int month, int dayOfMonth, int hour, int minute, int second, int nanoOfSecond)
public static LocalDateTime of(LocalDate date, LocalTime time) 
public static LocalDateTime ofInstant(Instant instant, ZoneId zone)
Copy the code
// Set the offset time zone
public OffsetDateTime atOffset(ZoneOffset offset) 
// Set the time zone,ZonedDateTime will be adjusted according to daylight saving time, purely in line with US policy
public ZonedDateTime atZone(ZoneId zone) 
// Intercept time to TemporalUnit
public Instant truncatedTo(TemporalUnit unit)
default Instant toInstant(ZoneOffset offset) 
default long toEpochSecond(ZoneOffset offset) 
Copy the code
  • Example LocalDateTime construct
LocalDateTime dateTime = LocalDateTime.of(2021.3.19.12.12.12.01);
System.out.println(dateTime);
dateTime = LocalDateTime.of(LocalDate.now(), LocalTime.now());
System.out.println(dateTime);
dateTime = LocalDateTime.parse("The 2021-03-19 12:12:12", DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")); System.out.println(dateTime); --------------- The command output is -----------------2021-03-19T12:12:12.000000001
2021-01-04T16:36:40.193887
2021-03-19T12:12:12
Copy the code
  • LocalDateTime Operation example
LocalDateTime dateTime = LocalDateTime.now();
// Set offset time zone to -6
OffsetDateTime offsetDateTime = dateTime.atOffset(ZoneOffset.ofHours(-6));
System.out.println(offsetDateTime);
// Set the time zone to the US time zone
ZonedDateTime zonedDateTime = dateTime.atZone(ZoneId.of("America/El_Salvador"));
System.out.println(zonedDateTime);
System.out.println(zonedDateTime.toEpochSecond());
// Output the timestamp of LocalDateTime, because LocalDateTime does not have a time zone, you need to specify a time zone
System.out.println(dateTime.toEpochSecond(ZoneOffset.ofHours(0)));
Copy the code

Period and Duration

  • Period The time span of the operation is year month day
public static Period of(int years, int months, int days)
public static Period between(LocalDate startDateInclusive, LocalDate endDateExclusive)
// Gets the unit of the current Period instance
public List<TemporalUnit> getUnits(a)
// Get the number of TemporalUnits
public long get(TemporalUnit unit)
public int getYears(a) 
public int getMonths(a) 
public int getDays(a) 
Copy the code
  • Duration The Duration of the operation is minutes and seconds
// Interval days Time difference between two days (unit: second)
public static Duration ofDays(long days)
// Interval hours Time difference between hours (in seconds)
public static Duration ofHours(long hours)
public static Duration ofSeconds(long seconds, long nanoAdjustment)
public static Duration parse(CharSequence text) 
public static Duration between(Temporal startInclusive, Temporal endExclusive)
public List<TemporalUnit> getUnits(a)
// The number of days between time differences. The unit of days is 0 if there is no time difference
public long toDaysPart(a)
// The number of hours of the time difference, the unit of hours, if not 0
public int toHoursPart(a)
// The number of minutes of the time difference, the unit of minutes, if not, is 0
public int toMinutesPart(a)
// The number of seconds in minutes, or 0 if not
public int toSecondsPart(a)
Copy the code
  • Use the sample
Duration duration = Duration.ofHours(1+24);
System.out.println("Days between:"+duration.toDaysPart());
System.out.println("Plus"+duration.toHoursPart()+"Hour"); --------------- Command output ----------------- Number of days between:1plus1hoursCopy the code

DateTimeFormatter

// Construct a time format class for the specified schema
public static DateTimeFormatter ofPattern(String pattern)
// Construct a timeformat class for the specified mode, and specify Locale
public static DateTimeFormatter ofPattern(String pattern, Locale locale)
public DateTimeFormatter withLocale(Locale locale) 
// The parsed time is with time zone
public DateTimeFormatter withZone(ZoneId zone)
// Get the current time zone
public ZoneId getZone(a) 
public String format(TemporalAccessor temporal)
// Parse the string as TemporalAccessor
public TemporalAccessor parse(CharSequence text) 
Copy the code
  • Use the sample
DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
dateTimeFormatter = dateTimeFormatter.withZone(ZoneId.of("America/El_Salvador"));
System.out.println(dateTimeFormatter.parse("The 2021-03-19 12:12:12"));
System.out.println(dateTimeFormatter.parse("The 2021-03-19 12:12:12").getLong(ChronoField.INSTANT_SECONDS)); -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- the output -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- {InstantSeconds =1616177532},ISO,America/El_Salvador resolved to 2021-03-19T12:12:12
1616177532
Copy the code

ZoneId and ZoneOffset

  • ZoneId indicates the time zone, which is adjusted according to daylight saving time. In different years, the ZonedDateTime corresponding to this ZoneId will change
public static ZoneId systemDefault(a)
// Get a collection of JDK supported Zoneids
public static Set<String> getAvailableZoneIds(a)
public static ZoneId of(String zoneId)
// Obtained under a TemporalAccessor entity, such as ZonedDateTime
public static ZoneId from(TemporalAccessor temporal)
Copy the code
  • ZoneOffset also represents a time zone, an offset from a fixed time. It doesn’t change for daylight saving time. It’s fixed
public static ZoneOffset of(String offsetId)
public static ZoneOffset ofHours(int hours) 
public static ZoneOffset ofHoursMinutesSeconds(int hours, int minutes, int seconds)
Copy the code

ZonedDateTime and OffsetDateTime

  • ZonedDateTime, corresponding to the combination of ZoneId and LocalDateTime
public static ZonedDateTime now(a)
public static ZonedDateTime ofInstant(Instant instant, ZoneId zone)
public static ZonedDateTime ofInstant(LocalDateTime localDateTime, ZoneOffset offset, ZoneId zone)
public static ZonedDateTime parse(CharSequence text, DateTimeFormatter formatter) 
public LocalDateTime toLocalDateTime(a)
public LocalDate toLocalDate(a) 
// Convert to OffsetDateTime (time zone becomes fixed, no longer dynamically adjusted according to DAYLIGHT saving time)
public OffsetDateTime toOffsetDateTime(a) 
Copy the code
  • OffsetDateTime, corresponding to the combination of ZoneOffset and LocalDateTime
public static OffsetDateTime of(LocalDate date, LocalTime time, ZoneOffset offset) 
public static OffsetDateTime of(LocalDateTime dateTime, ZoneOffset offset) 
public static OffsetDateTime ofInstant(Instant instant, ZoneId zone) 
public static OffsetDateTime parse(CharSequence text, DateTimeFormatter formatter)
// The current time is changed to offset the time in the time zone
public OffsetDateTime withOffsetSameInstant(ZoneOffset offset) 
Copy the code
  • Examples of ZonedDateTime and OffsetDateTime usage
System.out.println(LocalDateTime.now());
// The current time and change to America/Toronto time zone (with America/Toronto time zone, the time will be adjusted according to daylight saving time)
ZonedDateTime zonedDateTime = ZonedDateTime.ofInstant(Instant.now(), ZoneId.of("America/Toronto"));
System.out.println(zonedDateTime);
// The current time is converted to +0 time zone
OffsetDateTime offsetDateTime = OffsetDateTime.ofInstant(Instant.now(), ZoneOffset.of("+ 0")); System.out.println(offsetDateTime); --------------- The command output is ---------------------2021-01-10T15:07:08.072968
2021-01-10T02:07:08.073187-05:00[America/Toronto]
2021-01-10T07:07:08.075340Z
Copy the code

MonthDay and YearMonth

  • The operation class of MonthDay is MonthDay
public static MonthDay now(a)
public static MonthDay of(int month, int dayOfMonth)
public static MonthDay parse(CharSequence text, DateTimeFormatter formatter)
public LocalDate atYear(int year)
public Month getMonth(a)
// Total number of days in the current month
public int getDayOfMonth(a)
Copy the code
  • Year operation class YearMonth
public static YearMonth now(a)
public static YearMonth of(int year, int month) 
// Get YearMonth based on a time, if LocalDate
public static YearMonth from(TemporalAccessor temporal)
// Whether leap year
public boolean isLeapYear(a)
public Month getMonth(a)
public int getYear(a)
// Total number of days in the current year
public int lengthOfYear(a)
// Whether the number of days is valid in this month
public boolean isValidDay(int dayOfMonth)
public LocalDate atDay(int dayOfMonth)
Copy the code
  • Use the sample
MonthDay monthDay = MonthDay.of(3.19);
System.out.println(MonthDay.from(LocalDate.now()).isAfter(monthDay));
YearMonth yearMonth = YearMonth.of(2021.03);
System.out.println("Is 2021 a leap year?"+yearMonth.isLeapYear()); ------------ The command output is --------------false
2021Leap year or not:false
Copy the code

ChronoUnit

  • Units of time measurement, enumerated classes, inheriting TemporalUnit. It shows the units in which an interval is measured. For example, an interval of two days can be expressed as 48 hours. Generally used to set a time unit, add and subtract operations
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));
	/ / ChronoUnit definition
    private final String name;
    private final Duration duration;
    private ChronoUnit(String name, Duration estimatedDuration) {
        this.name = name;
        this.duration = estimatedDuration; }}Copy the code

ChronoField

  • Inherit TemporalField, enumerated classes. Similar to the ChronoUnit function, it is implemented based on TemporalUnit and is generally used to obtain values of different time domains
public enum ChronoField implements TemporalField {
    // Nanoseconds per second
    NANO_OF_SECOND("NanoOfSecond", NANOS, SECONDS, ValueRange.of(0.999 _999_999))
    // Seconds in a minute
    SECOND_OF_MINUTE("SecondOfMinute", SECONDS, MINUTES, ValueRange.of(0.59), "second")
    // The number of minutes in an hour
    MINUTE_OF_HOUR("MinuteOfHour", MINUTES, HOURS, ValueRange.of(0.59), "minute")
    // How many hours are there in a morning or afternoon
    CLOCK_HOUR_OF_AMPM("ClockHourOfAmPm", HOURS, HALF_DAYS, ValueRange.of(1.12))
    // The number of hours in a day
    CLOCK_HOUR_OF_DAY("ClockHourOfDay", HOURS, DAYS, ValueRange.of(1.24))
    // Morning or afternoon
    AMPM_OF_DAY("AmPmOfDay", HALF_DAYS, DAYS, ValueRange.of(0.1), "dayperiod")
    // The day of the week
    DAY_OF_WEEK("DayOfWeek", DAYS, WEEKS, ValueRange.of(1.7), "weekday")
    // Number of days in the current month
    DAY_OF_MONTH("DayOfMonth", DAYS, MONTHS, ValueRange.of(1.28.31), "day")
    // Number of days in the current year
    DAY_OF_YEAR("DayOfYear", DAYS, YEARS, ValueRange.of(1.365.366))
    // The week of the current month
    ALIGNED_WEEK_OF_MONTH("AlignedWeekOfMonth", WEEKS, MONTHS, ValueRange.of(1.4.5))
    // The number of weeks in the current year
    ALIGNED_WEEK_OF_YEAR("AlignedWeekOfYear", WEEKS, YEARS, ValueRange.of(1.53))
    // Take the first day of the month as Monday and calculate the day of the week
    ALIGNED_DAY_OF_WEEK_IN_MONTH("AlignedDayOfWeekInMonth", DAYS, WEEKS, ValueRange.of(1.7))
    // Take the first day of the month as Monday and calculate the day of the week
    ALIGNED_DAY_OF_WEEK_IN_YEAR("AlignedDayOfWeekInYear", DAYS, WEEKS, ValueRange.of(1.7))
    // Number of months in the current year
    MONTH_OF_YEAR("MonthOfYear", MONTHS, YEARS, ValueRange.of(1.12), "month")
    private final TemporalUnit baseUnit;
    private final String name;
    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;
    }
Copy the code
  • ALIGNED_WEEK_OF_MONTH and ALIGNED_DAY_OF_WEEK_IN_MONTH examples
// The 1st is Monday, every seven days. The 10th is the third day of the week
int num = LocalDateTime.now().get(ChronoField.ALIGNED_DAY_OF_WEEK_IN_MONTH);
System.out.println(num);
// The second week of the monthnum = LocalDateTime.now().get(ChronoField.ALIGNED_WEEK_OF_MONTH); System.out.println(num); ------------ The command output is --------------3
2
Copy the code

Interface for time conversion adjustment :TemporalAdjuster

  • Because java.time’s time classes are immutable, this method implementation is called when the time needs to be adjusted
  • The JDK provides a tool class called TemporalAdjusters for some default adjustment methods
// Implemented by subclasses
Temporal adjustInto(Temporal temporal)
Copy the code

TemporalAdjusters

  • Time adjustment utility class
// Set the day unit measure to the first day of the year
public static TemporalAdjuster firstDayOfYear(a)
// Set the day metric to the last day of the year
public static TemporalAdjuster lastDayOfYear(a)
// Set the time to the first day of the next year
public static TemporalAdjuster firstDayOfNextYear(a) 
// 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 ordinal week of the month -dayOfWeek
public static TemporalAdjuster dayOfWeekInMonth(int ordinal, DayOfWeek dayOfWeek)
// Set the time to next week's day
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 the last week -dayOfWeek
public static TemporalAdjuster previousOrSame(DayOfWeek dayOfWeek) 
Copy the code
  • The sample
LocalDateTime dateTime = LocalDateTime.now();
// Set the day field to the first day of the current month, other fields to the same value (now time is 202101)dateTime = dateTime.with(TemporalAdjusters.firstDayOfMonth()); System.out.println(dateTime); ------------ The command output is --------------2021-01-01T14:50:40.659823
Copy the code

Date and LocalDateTime interconvert

  • Datetime = datetime; datetime = LocalDateTime; Date = LocalDateTime
  • The sample
/ / Date LocalDateTime
Date date = newDate(); LocalDateTime dateTime = LocalDateTime.ofInstant(date.toInstant(), ZoneId.systemDefault()); System.out.println(dateTime); dateTime = LocalDateTime.ofInstant(Instant.ofEpochMilli(date.getTime()), ZoneId.systemDefault()); System.out.println(dateTime); ------------ The command output is ------------2021-01-10T14:25:08.649
2021-01-10T14:25:08.649
Copy the code
/ / LocalDateTime DateLocalDateTime localDateTime = LocalDateTime.now(); Date date = Date.from(localDateTime.atZone(ZoneId.systemDefault()).toInstant()); System.out.println(date); ------------ Command output ------------ Sun Jan10 14:29:04 CST 2021
Copy the code

Corrections are welcome

Refer to the article

  • JAVA8 time class library with JodaTime
  • New features in JDK8 – New time and date APIS