Basic part: jdk8 date processing API

Sneak on 2021-01-21 17:47:59
basic jdk8 jdk date processing


Preface

jdk8 We've been using Date、Calender and SimpleDateFormat, But its API Not strong enough , There are also thread safety issues , Has been criticized .jdk8 Provides new time API, stay java.time The classes in the package are immutable and thread safe , It and Joda By the same author , So we can learn from Joda Many features , If you use habits Joda, It's easy to switch to java.time The use of the class

Official account , Communicate together , Search on wechat : Sneak forward

java.time Class

  • Date and time Make a distinction ,Date( date ) My unit is year, month, day .time( Time ) It's in hours, minutes and seconds

class

describe

Instant

Time stamp ( Instantaneous time , With time zone )

LocalDate

date ( such as :2018-09-24, No time zone )

LocalTime

Time ( such as :10:32:10, No time zone )

LocalDateTime

Date time ( such as :2018-09-24 10:32:10, No time zone )

Duration

The difference between the two times , Accurate to seconds or nanoseconds

Peroid

The difference between the two dates ( Accurate to the day )

DateTimeFormatter

Date time format class

ZoneId

The time zone

ZoneOffset

Time zone offset ( such as :+8:00)

ZonedDateTime

Date time with time zone

ChronoUnit

Date enumeration class ( In time addition and subtraction operations can be used to )

MonthDay

Month day

YearMonth

years

Clock The clock

  • Clock It's the clock associated with the time zone ,Clock You can get the time stamp and time zone ZoneId, Used in place of System.currentTimeMillis() and TimeZone.getDefault(). It's an abstract class , There are four subcategories
public static Clock systemDefaultZone()
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 time zone
public abstract ZoneId getZone()
// Designated time zone
public abstract Clock withZone(ZoneId zone)
// Get the timestamp
public abstract Instant instant()
  • System default local clock SystemClock
Clock clock = Clock.systemDefaultZone();
System.out.println(clock.getZone());
Instant instant = clock.instant();
System.out.println(instant);
---------- Output results -----------
Asia/Shanghai
2021-01-03T05:05:31.791Z
1609650331791
  • Offset clock OffsetClock
Clock clock = Clock.systemDefaultZone();
Clock pastClock = Clock.offset(clock, Duration.ofMillis(-10000));
System.out.println(pastClock.getZone());
// The present time and the past pastClock Difference between 10000 millisecond
System.out.println(clock.millis() - pastClock.millis());
---------- Output results -----------
10000
  • It's periodic TickDuration, Intercept the time to the nearest last cycle or next cycle . Be careful :TickDuration The current time point will not be used as the start time of the cycle
Clock clock = Clock.systemDefaultZone();
Clock nearestHourClock = Clock.tick(clock, Duration.ofMillis(10));
// The current time is 2021-01-03T05:36:54.088Z, Period is 10 millisecond ,TickDuration Automatically
// choice 2021-01-03T05:36:54.090Z As the starting time
System.out.println(clock.instant());
System.out.println(nearestHourClock.instant());
Thread.sleep(10);
System.out.println(clock.instant());
System.out.println(nearestHourClock.instant());
---------- Output results -----------
2021-01-03T05:43:19.088Z
2021-01-03T05:43:19.090Z
2021-01-03T05:43:19.107Z
2021-01-03T05:43:19.100Z
  • Time doesn't change 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());
---------- Output results -----------
2021-01-03T05:27:43.272Z
2021-01-03T05:27:43.272Z

Temporal

  • The unified interface of time class , Define some common method operations , Such as : The addition and subtraction of a time unit , Set the time field to a fixed value
public interface Temporal extends TemporalAccessor {
// Get what the time class can represent TemporalField Range value
public ValueRange range(TemporalField field)
// Set up TemporalField The value of the time domain
public Temporal with(TemporalField field, long newValue)
// according to TemporalAdjuster Interface conversion time
public Temporal with(TemporalAdjuster adjuster)
// Increase the specified TemporalUnit The number of units
public Temporal plus(long amountToAdd, TemporalUnit unit)
// Reduce designation TemporalUnit The number of units
public Temporal minus(long amountToSubtract, TemporalUnit unit)
  • Temporal Subclasses of

Instant

  • Instant It's used to manipulate timestamps , With time zone , Default UTC Greenwich time zone . So other time classes and Instant When we turn around , You need to specify your own time zone
public static Instant now()
public static Instant now(Clock clock)
// Generated in milliseconds Instant
public static Instant ofEpochMilli(long epochMilli)
// Generated in seconds Instant, The number of nanosecond units attached to it
public static Instant ofEpochSecond(long epochSecond, long nanoAdjustment)
//text The format of :2021-01-04T06:37:53.743Z
public static Instant parse(CharSequence text)
// Calculation and Temporal The time difference between , With TemporalUnit Measure... In units
public long until(Temporal endExclusive, TemporalUnit unit) 
  • Time stamp creation
Instant instant = Instant.now();
System.out.println(instant);
instant = Instant.now(Clock.systemDefaultZone());
System.out.println(instant);
// and Date Mutual conversion of
instant = Instant.ofEpochMilli(new Date().getTime());
System.out.println(instant);
// According to the string generation time , Support to nanosecond level
instant = Instant.parse("1995-10-23T10:12:35.999999999Z");
System.out.println(instant);
// According to the second and the nanosecond of the deviation Create timestamps
Instant preInstant = Instant.ofEpochSecond(1609741558,1);
// The difference between the past time and the current time , You can specify units TemporalUnit
System.out.println(preInstant.until(Instant.now(), ChronoUnit.MINUTES));
--------------- Output results ------------------------
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
  • Instant Use
Instant instant = Instant.now();
// Set the time zone as America/El_Salvador( The United States )
ZonedDateTime zonedDateTime = instant.atZone(ZoneId.of("America/El_Salvador"));
System.out.println(zonedDateTime);
// Set the time zone to offset -6 The time zone ( The United States )
OffsetDateTime offsetDateTime = instant.atOffset(ZoneOffset.ofHours(-6));
System.out.println(offsetDateTime);
// Days plus 2, Minutes minus 1. The number of months is set to 12 month
Instant fixInstant = instant.minus(1, ChronoUnit.MINUTES)
.plus(2, ChronoUnit.DAYS);
System.out.println(instant);
System.out.println(fixInstant);
--------------- Output results -----------------
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

LocalTime

  • LocalTime It's a class for operating hours, minutes and seconds , Plus nanosecond accuracy ; No concept of time zone , turn Instant You need to set the time zone first
  • LocalTime Construction method of
public static LocalTime now()
public static LocalTime of(int hour, int minute, int second, int nanoOfSecond)
// Seconds before dawn
public static LocalTime ofSecondOfDay(long secondOfDay)
// Nanoseconds before dawn
public static LocalTime ofNanoOfDay(long nanoOfDay)
public static LocalTime parse(CharSequence text, DateTimeFormatter formatter)
//jdk9
public static LocalTime ofInstant(Instant instant, ZoneId zone)
  • LocalTime Conversion with other time classes
public LocalDateTime atDate(LocalDate date)
public OffsetTime atOffset(ZoneOffset offset)
public long toEpochSecond(LocalDate date, ZoneOffset offset)
  • LocalTime Create an example
// 1 The unit of measurement is 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);
--------------- Output results -----------------
12:12:12.000000001
12:12
12:12:12
  • LocalTime Common methods of dealing with
LocalTime localTime = LocalTime.of(12, 12, 12, 1);
System.out.println(localTime);
// Splicing date , Generation date time
LocalDateTime dateTime = localTime.atDate(LocalDate.now());
System.out.println(dateTime);
// Set time zone , The amount of time doesn't change
OffsetTime offsetTime = LocalTime.now().atOffset(ZoneOffset.ofHours(-6));
System.out.println(offsetTime);
// Current time plus date , And set the time zone to offset
long seconds = LocalTime.now().toEpochSecond(LocalDate.now(), ZoneOffset.ofHours(-6));
System.out.println(seconds);
--------------- Output results -----------------
12:12:12.000000001
2021-01-04T12:12:12.000000001
16:29:33.917387700-06:00
1609799373

LocalDate

  • LocalDate Is a class used to operate the date of the year ; The unit of time is the deadline , It doesn't include hours and units after that
public static LocalDate now()
public static LocalDate of(int year, int month, int dayOfMonth)
public static LocalDate ofInstant(Instant instant, ZoneId zone)
// That day is the day of the month
public int getDayOfMonth()
// It was the first day of the year
public int getDayOfYear()
// That day is the day of the week (1~7)
public DayOfWeek getDayOfWeek()
// Leap year or not
public boolean isLeapYear()
public LocalDateTime atTime(LocalTime time)
// Set the time to early this morning
public LocalDateTime atStartOfDay()
// The following two methods are jdk9, Get the current time to endExclusive Every date of
public Stream<LocalDate> datesUntil(LocalDate endExclusive)
public Stream<LocalDate> datesUntil(LocalDate endExclusive, Period step) 
  • LocalDate Create an example of
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);
--------------- Output results -----------------
2021-01-04
2020-03-19
2021-03-19
  • LocalDate The operation of
LocalDate localDate = LocalDate.parse("20210319", DateTimeFormatter.BASIC_ISO_DATE);
System.out.println(" What day of the current year :" + localDate.getDayOfYear() + "; The day of the current month " + localDate.getDayOfMonth()+"; What day of the week :"+localDate.getDayOfWeek());
// Add LocalTime Turn into LocalDateTime
LocalDateTime dateTime = localDate.atTime(LocalTime.now());
System.out.println(dateTime);
--------------- Output results -----------------
What day of the current year :78; The day of the current month 19; What day of the week :FRIDAY
2021-03-19T15:37:54.713

LocalDateTime

  • amount to LocalDate and LocalTime The combination of , Class used to represent year, year, day, hour, minute and second , Plus nanosecond accuracy ; No concept of time zone , turn Instant You need to set the time zone first
public static LocalDateTime now()
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)
// Set the offset time zone
public OffsetDateTime atOffset(ZoneOffset offset)
// Set time zone ,ZonedDateTime It'll be based on the summer time , It's purely in line with US policy
public ZonedDateTime atZone(ZoneId zone)
// It's time to intercept TemporalUnit Company
public Instant truncatedTo(TemporalUnit unit)
default Instant toInstant(ZoneOffset offset)
default long toEpochSecond(ZoneOffset offset) 
  • LocalDateTime Construction examples
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("2021-03-19 12:12:12", DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
System.out.println(dateTime);
--------------- Output results -----------------
2021-03-19T12:12:12.000000001
2021-01-04T16:36:40.193887
2021-03-19T12:12:12
  • LocalDateTime The operation sample
LocalDateTime dateTime = LocalDateTime.now();
// Set the offset time zone to -6
OffsetDateTime offsetDateTime = dateTime.atOffset(ZoneOffset.ofHours(-6));
System.out.println(offsetDateTime);
// Set the time zone to the U.S. time zone
ZonedDateTime zonedDateTime = dateTime.atZone(ZoneId.of("America/El_Salvador"));
System.out.println(zonedDateTime);
System.out.println(zonedDateTime.toEpochSecond());
// Output LocalDateTime The timestamp , because LocalDateTime It doesn't have a time zone , Time zone needs to be specified
System.out.println(dateTime.toEpochSecond(ZoneOffset.ofHours(0)));

Period and Duration

  • Period The time span of the operation is mm / DD / yyyy
public static Period of(int years, int months, int days)
public static Period between(LocalDate startDateInclusive, LocalDate endDateExclusive)
// Get current Period Unit of instance
public List<TemporalUnit> getUnits()
// obtain TemporalUnit The number of
public long get(TemporalUnit unit)
public int getYears()
public int getMonths()
public int getDays() 
  • Duration The time span of the operation is hours, minutes and seconds , Plus nanoseconds
// interval days The time difference between two days ( Unit second )
public static Duration ofDays(long days)
// interval hours Time difference in hours ( Unit second )
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()
// The number of days between time differences , Days unit part , If not, it is 0
public long toDaysPart()
// The hour span of the time difference , The unit part of the hour , If not, it is 0
public int toHoursPart()
// The minute span of the time difference , The minute unit part , If not, it is 0
public int toMinutesPart()
// The second span of the time difference , Seconds in minutes , If not, it is 0
public int toSecondsPart()
  • Examples of use
Duration duration = Duration.ofHours(1+24);
System.out.println(" Days apart :"+duration.toDaysPart());
System.out.println(" Plus "+duration.toHoursPart()+" Hours ");
--------------- Output results -----------------
Days apart :1
Plus 1 Hours 

DateTimeFormatter

// Construct the time format class of the specified pattern
public static DateTimeFormatter ofPattern(String pattern)
// Construct the time format class of the specified pattern , And designate 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()
public String format(TemporalAccessor temporal)
// The parsing string is TemporalAccessor
public TemporalAccessor parse(CharSequence text) 
  • Examples of use
DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
dateTimeFormatter = dateTimeFormatter.withZone(ZoneId.of("America/El_Salvador"));
System.out.println(dateTimeFormatter.parse("2021-03-19 12:12:12"));
System.out.println(dateTimeFormatter.parse("2021-03-19 12:12:12").getLong(ChronoField.INSTANT_SECONDS));
--------------- Output results -----------------
{InstantSeconds=1616177532},ISO,America/El_Salvador resolved to 2021-03-19T12:12:12
1616177532

ZoneId and ZoneOffset

  • ZoneId Time zone , It will be adjusted according to daylight saving time . In different years and times , The ZoneId Corresponding ZonedDateTime Will change
public static ZoneId systemDefault()
// obtain jdk Supported by ZoneId Set
public static Set<String> getAvailableZoneIds()
public static ZoneId of(String zoneId)
// According to a TemporalAccessor Entity acquisition of , Such as :ZonedDateTime
public static ZoneId from(TemporalAccessor temporal)
  • ZoneOffset It also means time zone , Fixed time offset . It won't be adjusted to daylight saving time , unchanging
public static ZoneOffset of(String offsetId)
public static ZoneOffset ofHours(int hours)
public static ZoneOffset ofHoursMinutesSeconds(int hours, int minutes, int seconds)

ZonedDateTime and OffsetDateTime

  • ZonedDateTime, Corresponding ZoneId Add LocalDateTime The combination of
public static ZonedDateTime now()
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()
public LocalDate toLocalDate()
// Turn into OffsetDateTime( Time zones become fixed , No longer dynamically adjust to daylight saving time )
public OffsetDateTime toOffsetDateTime() 
  • OffsetDateTime, Corresponding ZoneOffset Add LocalDateTime The combination of
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 changes to offset The time zone represents the time
public OffsetDateTime withOffsetSameInstant(ZoneOffset offset) 
  • ZonedDateTime and OffsetDateTime Examples of use
System.out.println(LocalDateTime.now());
// Current time and change to America/Toronto Time zone time ( belt America/Toronto The 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);
// Current time and change to +0 Time zone time
OffsetDateTime offsetDateTime = OffsetDateTime.ofInstant(Instant.now(), ZoneOffset.of("+0"));
System.out.println(offsetDateTime);
--------------- Output results ---------------------
2021-01-10T15:07:08.072968
2021-01-10T02:07:08.073187-05:00[America/Toronto]
2021-01-10T07:07:08.075340Z

MonthDay and YearMonth

  • Month day operation class MonthDay
public static MonthDay now()
public static MonthDay of(int month, int dayOfMonth)
public static MonthDay parse(CharSequence text, DateTimeFormatter formatter)
public LocalDate atYear(int year)
public Month getMonth()
// The total number of days in the current month
public int getDayOfMonth()
  • Operation class of month and year YearMonth
public static YearMonth now()
public static YearMonth of(int year, int month)
// Get... According to a time YearMonth, If LocalDate
public static YearMonth from(TemporalAccessor temporal)
// Leap year or not
public boolean isLeapYear()
public Month getMonth()
public int getYear()
// The total number of days in the current year
public int lengthOfYear()
// Whether this number of days is valid in this month
public boolean isValidDay(int dayOfMonth)
public LocalDate atDay(int dayOfMonth)
  • Examples of use
MonthDay monthDay = MonthDay.of(3,19);
System.out.println(MonthDay.from(LocalDate.now()).isAfter(monthDay));
YearMonth yearMonth = YearMonth.of(2021,03);
System.out.println("2021 Is it a leap year :"+yearMonth.isLeapYear());
------------ Output results --------------
false
2021 Is it a leap year :false

ChronoUnit

  • Time unit of measure , Enumeration class , Inherit TemporalUnit. It represents a time interval in what units , For example, the interval between two days can be used 48 An hour instead of . It is generally used for setting a certain time unit , Add and subtract
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 The definition of
private final String name;
private final Duration duration;
private ChronoUnit(String name, Duration estimatedDuration) {
this.name = name;
this.duration = estimatedDuration;
}
}

ChronoField

  • Inherit TemporalField, Enumeration class . and ChronoUnit The function is similar to , be based on TemporalUnit Realization , It is generally used to obtain values in different time domains
public enum ChronoField implements TemporalField {
// Nanoseconds in a 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")
// 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 hours of the 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")
// The number of days in the current month
DAY_OF_MONTH("DayOfMonth", DAYS, MONTHS, ValueRange.of(1, 28, 31), "day")
// The number of days in the current year
DAY_OF_YEAR("DayOfYear", DAYS, YEARS, ValueRange.of(1, 365, 366))
// The number of weeks in 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 every month as Monday , Then calculate the day of the week
ALIGNED_DAY_OF_WEEK_IN_MONTH("AlignedDayOfWeekInMonth", DAYS, WEEKS, ValueRange.of(1, 7))
// Take the first day of every month as Monday , Then calculate the day of the week
ALIGNED_DAY_OF_WEEK_IN_YEAR("AlignedDayOfWeekInYear", DAYS, WEEKS, ValueRange.of(1, 7))
// The 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;
}
  • ALIGNED_WEEK_OF_MONTH and ALIGNED_DAY_OF_WEEK_IN_MONTH Examples of use
// With 1 It's Monday , Every seven days a week ,10 It's 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 month
num = LocalDateTime.now().get(ChronoField.ALIGNED_WEEK_OF_MONTH);
System.out.println(num);
------------ Output results --------------
3
2

Time conversion adjustment interface :TemporalAdjuster

  • because java.time All time classes are immutable , So when you need to adjust the time , You can call this method to implement
  • jdk Provides some tool classes for default adjustment methods TemporalAdjusters
// Implemented by subclasses
Temporal adjustInto(Temporal temporal)

TemporalAdjusters

  • Time adjustment tools
// Set the day unit measure to the first day of the year
public static TemporalAdjuster firstDayOfYear()
// Set the day unit measure 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... Of the month ordinal What day of the week -dayOfWeek
public static TemporalAdjuster dayOfWeekInMonth(int ordinal, DayOfWeek dayOfWeek)
// Set the time for 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 number of weeks and dayOfWeek Dissimilarity , Set the time to the day of last week -dayOfWeek
public static TemporalAdjuster previousOrSame(DayOfWeek dayOfWeek) 
  • Example
LocalDateTime dateTime = LocalDateTime.now();
// Set the value of the day area to the first day of the current month , The values of the other fields remain unchanged ( Now the time is 202101)
dateTime = dateTime.with(TemporalAdjusters.firstDayOfMonth());
System.out.println(dateTime);
------------ Output results --------------
2021-01-01T14:50:40.659823

Date and LocalDateTime Interturn

  • JDK1.8 The time used before is Date, For compatibility , We need to know ,Date and LocalDateTime Conversion between
  • Example
//Date turn LocalDateTime
Date date = new Date();
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);
------------ Output results ------------
2021-01-10T14:25:08.649
2021-01-10T14:25:08.649
//LocalDateTime turn Date
LocalDateTime localDateTime = LocalDateTime.now();
Date date = Date.from(localDateTime.atZone(ZoneId.systemDefault()).toInstant());
System.out.println(date);
------------ Output results ------------
Sun Jan 10 14:29:04 CST 2021

Welcome refers to a mistake in the text

Reference article

  • JAVA8 Time class library and JodaTime[1]
  • JDK8 New characteristics - New time and date API[2]

Reference

[1]

JAVA8 Time class library and JodaTime: https://blog.csdn.net/zzz_zjz/article/details/93030049

[2]

JDK8 New characteristics - New time and date API: https://blog.csdn.net/qq_37581282/article/details/108610492

This article is from WeChat official account. - Sneak forward (qianxingcsc)

The source and reprint of the original text are detailed in the text , If there is any infringement , Please contact the yunjia_community@tencent.com Delete .

Original publication time : 2021-01-15

Participation of this paper Tencent cloud media sharing plan , You are welcome to join us , share .

版权声明
本文为[Sneak on]所创,转载请带上原文链接,感谢
https://javamana.com/2021/01/20210121174556318d.html

  1. 【计算机网络 12(1),尚学堂马士兵Java视频教程
  2. 【程序猿历程,史上最全的Java面试题集锦在这里
  3. 【程序猿历程(1),Javaweb视频教程百度云
  4. Notes on MySQL 45 lectures (1-7)
  5. [computer network 12 (1), Shang Xuetang Ma soldier java video tutorial
  6. The most complete collection of Java interview questions in history is here
  7. [process of program ape (1), JavaWeb video tutorial, baidu cloud
  8. Notes on MySQL 45 lectures (1-7)
  9. 精进 Spring Boot 03:Spring Boot 的配置文件和配置管理,以及用三种方式读取配置文件
  10. Refined spring boot 03: spring boot configuration files and configuration management, and reading configuration files in three ways
  11. 精进 Spring Boot 03:Spring Boot 的配置文件和配置管理,以及用三种方式读取配置文件
  12. Refined spring boot 03: spring boot configuration files and configuration management, and reading configuration files in three ways
  13. 【递归,Java传智播客笔记
  14. [recursion, Java intelligence podcast notes
  15. [adhere to painting for 386 days] the beginning of spring of 24 solar terms
  16. K8S系列第八篇(Service、EndPoints以及高可用kubeadm部署)
  17. K8s Series Part 8 (service, endpoints and high availability kubeadm deployment)
  18. 【重识 HTML (3),350道Java面试真题分享
  19. 【重识 HTML (2),Java并发编程必会的多线程你竟然还不会
  20. 【重识 HTML (1),二本Java小菜鸟4面字节跳动被秒成渣渣
  21. [re recognize HTML (3) and share 350 real Java interview questions
  22. [re recognize HTML (2). Multithreading is a must for Java Concurrent Programming. How dare you not
  23. [re recognize HTML (1), two Java rookies' 4-sided bytes beat and become slag in seconds
  24. 造轮子系列之RPC 1:如何从零开始开发RPC框架
  25. RPC 1: how to develop RPC framework from scratch
  26. 造轮子系列之RPC 1:如何从零开始开发RPC框架
  27. RPC 1: how to develop RPC framework from scratch
  28. 一次性捋清楚吧,对乱糟糟的,Spring事务扩展机制
  29. 一文彻底弄懂如何选择抽象类还是接口,连续四年百度Java岗必问面试题
  30. Redis常用命令
  31. 一双拖鞋引发的血案,狂神说Java系列笔记
  32. 一、mysql基础安装
  33. 一位程序员的独白:尽管我一生坎坷,Java框架面试基础
  34. Clear it all at once. For the messy, spring transaction extension mechanism
  35. A thorough understanding of how to choose abstract classes or interfaces, baidu Java post must ask interview questions for four consecutive years
  36. Redis common commands
  37. A pair of slippers triggered the murder, crazy God said java series notes
  38. 1、 MySQL basic installation
  39. Monologue of a programmer: despite my ups and downs in my life, Java framework is the foundation of interview
  40. 【大厂面试】三面三问Spring循环依赖,请一定要把这篇看完(建议收藏)
  41. 一线互联网企业中,springboot入门项目
  42. 一篇文带你入门SSM框架Spring开发,帮你快速拿Offer
  43. 【面试资料】Java全集、微服务、大数据、数据结构与算法、机器学习知识最全总结,283页pdf
  44. 【leetcode刷题】24.数组中重复的数字——Java版
  45. 【leetcode刷题】23.对称二叉树——Java版
  46. 【leetcode刷题】22.二叉树的中序遍历——Java版
  47. 【leetcode刷题】21.三数之和——Java版
  48. 【leetcode刷题】20.最长回文子串——Java版
  49. 【leetcode刷题】19.回文链表——Java版
  50. 【leetcode刷题】18.反转链表——Java版
  51. 【leetcode刷题】17.相交链表——Java&python版
  52. 【leetcode刷题】16.环形链表——Java版
  53. 【leetcode刷题】15.汉明距离——Java版
  54. 【leetcode刷题】14.找到所有数组中消失的数字——Java版
  55. 【leetcode刷题】13.比特位计数——Java版
  56. oracle控制用户权限命令
  57. 三年Java开发,继阿里,鲁班二期Java架构师
  58. Oracle必须要启动的服务
  59. 万字长文!深入剖析HashMap,Java基础笔试题大全带答案
  60. 一问Kafka就心慌?我却凭着这份,图灵学院vip课程百度云