前言

jdk8之前咱们始终在用Date、Calender和SimpleDateFormat,但它的API不够弱小,还存在线程平安问题,始终被人诟病。jdk8提供了新的工夫API,在java.time包里的类是不可变且线程平安的,它和Joda是同一个作者实现的,因而借鉴了Joda很多特点,如果你用习惯Joda,能够很不便地切换到java.time类的应用

关注公众号,一起交换,微信搜一搜: 潜行前行

java.time类的简略介绍

  • Date和time做下辨别,Date(日期)的单位是年月日。time(工夫)的单位是时分秒
类 形容
Instant   工夫戳(刹时工夫,带时区)
LocalDate  日期(比方:2018-09-24,不带时区)
LocalTime  工夫(比方:10:32:10,不带时区)
LocalDateTime    日期工夫(比方:2018-09-24 10:32:10,不带时区)
Duration  两个工夫的差,准确到秒或纳秒
Peroid    两个日期的差(准确到日)
DateTimeFormatter  日期工夫格式化类
ZoneId         时区
ZoneOffset 时区偏移量(比方:+8:00)
ZonedDateTime     带时区的日期工夫
ChronoUnit      日期枚举类(在工夫加减操作可用到)
MonthDay  月日
YearMonth  年月

Clock时钟

  • Clock是关联上时区的时钟,Clock能够获取工夫戳和时区ZoneId,用来代替System.currentTimeMillis()和TimeZone.getDefault()。它是个抽象类,一共有四个子类

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) --------上面办法由下面四个子类实现---------//获取时区public abstract ZoneId getZone()//指定时区public abstract Clock withZone(ZoneId zone)//获取工夫戳public abstract Instant instant()
  • 零碎默认本地时钟SystemClock
Clock clock = Clock.systemDefaultZone();System.out.println(clock.getZone());Instant instant = clock.instant();System.out.println(instant);----------输入后果-----------Asia/Shanghai2021-01-03T05:05:31.791Z1609650331791
  • 偏移时钟OffsetClock
Clock clock = Clock.systemDefaultZone();Clock pastClock = Clock.offset(clock, Duration.ofMillis(-10000));System.out.println(pastClock.getZone());//以后工夫和过来pastClock相差10000毫秒System.out.println(clock.millis() - pastClock.millis());----------输入后果-----------10000
  • 周期计时的TickDuration,截取工夫到最靠近的上个周期或下个周期的工夫。留神:TickDuration不会把以后工夫点作为周期的起始工夫
Clock clock = Clock.systemDefaultZone();Clock nearestHourClock = Clock.tick(clock, Duration.ofMillis(10));//以后工夫是2021-01-03T05:36:54.088Z,周期是10毫秒,TickDuration主动//抉择2021-01-03T05:36:54.090Z作为起始工夫System.out.println(clock.instant());System.out.println(nearestHourClock.instant());Thread.sleep(10);System.out.println(clock.instant());System.out.println(nearestHourClock.instant());----------输入后果-----------2021-01-03T05:43:19.088Z2021-01-03T05:43:19.090Z2021-01-03T05:43:19.107Z2021-01-03T05:43:19.100Z
  • 工夫不变的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());----------输入后果-----------2021-01-03T05:27:43.272Z2021-01-03T05:27:43.272Z

Temporal

  • 工夫类的对立接口,定义一些通用的办法操作,如:某工夫单位的加减,设置为工夫域为某一固定值
public interface Temporal extends TemporalAccessor {    //获取工夫类能示意的TemporalField范畴值    public ValueRange range(TemporalField field)    //设置TemporalField工夫域的值    public Temporal with(TemporalField field, long newValue)    //依据TemporalAdjuster接口转化工夫    public Temporal with(TemporalAdjuster adjuster)    //减少指定TemporalUnit单位的数量    public Temporal plus(long amountToAdd, TemporalUnit unit)    //缩小指定TemporalUnit单位的数量    public Temporal minus(long amountToSubtract, TemporalUnit unit)
  • Temporal的子类

Instant

  • Instant是用来操作工夫戳的,带时区,默认UTC的格林威治时区。因而其余工夫类和Instant互转时,须要指定本人的时区
public static Instant now()public static Instant now(Clock clock)//依据毫秒生成Instantpublic static Instant ofEpochMilli(long epochMilli)//依据秒生成Instant,外附加纳秒单位的数值public static Instant ofEpochSecond(long epochSecond, long nanoAdjustment)//text的格局:2021-01-04T06:37:53.743Zpublic static Instant parse(CharSequence text) //计算与Temporal相隔的时间差,以TemporalUnit为单位度量public long until(Temporal endExclusive, TemporalUnit unit) 
  • 工夫戳的创立
Instant instant = Instant.now();System.out.println(instant);instant = Instant.now(Clock.systemDefaultZone());System.out.println(instant);//和Date的互相转换instant = Instant.ofEpochMilli(new Date().getTime());System.out.println(instant);//依据字符串生成工夫,反对到纳秒级别instant = Instant.parse("1995-10-23T10:12:35.999999999Z");System.out.println(instant);//依据秒和偏差的纳秒 创立工夫戳Instant preInstant = Instant.ofEpochSecond(1609741558,1);//过来工夫和以后工夫的相差值,能够指定单位TemporalUnitSystem.out.println(preInstant.until(Instant.now(), ChronoUnit.MINUTES));---------------输入后果------------------------2021-01-04T06:37:53.743Z2021-01-04T06:37:53.795Z2021-01-04T06:37:53.795Z1995-10-23T10:12:35.999999999Z2021-01-04T06:25:58.000000001Z2021-01-04T06:37:53.798Z11
  • Instant的应用
Instant instant = Instant.now();//设置时区为America/El_Salvador(美国)ZonedDateTime zonedDateTime = instant.atZone(ZoneId.of("America/El_Salvador"));System.out.println(zonedDateTime);//设置时区为偏移-6的时区(美国)OffsetDateTime offsetDateTime = instant.atOffset(ZoneOffset.ofHours(-6));System.out.println(offsetDateTime);//天数加2,分钟数减1。月数设定为12月Instant fixInstant = instant.minus(1, ChronoUnit.MINUTES)        .plus(2, ChronoUnit.DAYS);System.out.println(instant);System.out.println(fixInstant);---------------输入后果-----------------2021-01-04T00:53:01.895-06:00[America/El_Salvador]2021-01-04T00:53:01.895-06:002021-01-04T06:53:01.895Z2021-01-06T06:52:01.895Z

LocalTime

  • LocalTime是用来操作时分秒的类,外加准确到纳秒级别;无时区概念,转Instant须要先设置时区
  • LocalTime的构造方法
public static LocalTime now() public static LocalTime of(int hour, int minute, int second, int nanoOfSecond)//间隔凌晨的秒数public static LocalTime ofSecondOfDay(long secondOfDay)//间隔凌晨的纳秒数public static LocalTime ofNanoOfDay(long nanoOfDay)public static LocalTime parse(CharSequence text, DateTimeFormatter formatter) //jdk9public static LocalTime ofInstant(Instant instant, ZoneId zone)
  • LocalTime与其余工夫类的转换
public LocalDateTime atDate(LocalDate date)public OffsetTime atOffset(ZoneOffset offset) public long toEpochSecond(LocalDate date, ZoneOffset offset)
  • LocalTime创立示例
//  1的单位是纳秒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);---------------输入后果-----------------12:12:12.00000000112:1212:12:12
  • LocalTime的罕用解决办法
LocalTime localTime = LocalTime.of(12, 12, 12, 1);System.out.println(localTime);//拼接日期,生成日期工夫LocalDateTime dateTime = localTime.atDate(LocalDate.now());System.out.println(dateTime);//设定时区,工夫量不变OffsetTime offsetTime = LocalTime.now().atOffset(ZoneOffset.ofHours(-6));System.out.println(offsetTime);//以后工夫加日期,并设置时区为offsetlong seconds = LocalTime.now().toEpochSecond(LocalDate.now(), ZoneOffset.ofHours(-6));System.out.println(seconds);---------------输入后果-----------------12:12:12.0000000012021-01-04T12:12:12.00000000116:29:33.917387700-06:001609799373

LocalDate

  • LocalDate是用来操作年月日的类;示意的工夫单位是截止到日,不包含小时及前面的单位
public static LocalDate now()public static LocalDate of(int year, int month, int dayOfMonth)public static LocalDate ofInstant(Instant instant, ZoneId zone)
//当天是当月的第几天public int getDayOfMonth()//当天是当年的第几天public int getDayOfYear()//当天是当周的第几天(1~7)public DayOfWeek getDayOfWeek() //是否平年public boolean isLeapYear() public LocalDateTime atTime(LocalTime time)//设置工夫为明天的凌晨public LocalDateTime atStartOfDay()//以下两个办法是jdk9,获取以后工夫到endExclusive的每一个日期public Stream<LocalDate> datesUntil(LocalDate endExclusive)public Stream<LocalDate> datesUntil(LocalDate endExclusive, Period step) 
  • 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);---------------输入后果-----------------2021-01-042020-03-192021-03-19
  • LocalDate的操作
LocalDate localDate = LocalDate.parse("20210319", DateTimeFormatter.BASIC_ISO_DATE);System.out.println("以后年的第几天:" + localDate.getDayOfYear() + "; 以后月的第几天" + localDate.getDayOfMonth()+"; 以后星期几:"+localDate.getDayOfWeek());//加LocalTime转变为LocalDateTimeLocalDateTime dateTime = localDate.atTime(LocalTime.now());System.out.println(dateTime);---------------输入后果-----------------以后年的第几天:78; 以后月的第几天19; 以后星期几:FRIDAY2021-03-19T15:37:54.713

LocalDateTime

  • 相当于LocalDate 和 LocalTime的联合,用来示意年月日时分秒的类,外加准确到纳秒级别;无时区概念,转Instant须要先设置时区
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)
//设置偏移时区public OffsetDateTime atOffset(ZoneOffset offset) //设置时区,ZonedDateTime会依据夏令时调的,纯正是配合美国政策的货色public ZonedDateTime atZone(ZoneId zone) //截取工夫到TemporalUnit单位public Instant truncatedTo(TemporalUnit unit)default Instant toInstant(ZoneOffset offset) default long toEpochSecond(ZoneOffset offset) 
  • LocalDateTime结构示例
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);---------------输入后果-----------------2021-03-19T12:12:12.0000000012021-01-04T16:36:40.1938872021-03-19T12:12:12
  • LocalDateTime操作示例
LocalDateTime dateTime = LocalDateTime.now();//设置偏移时区为-6OffsetDateTime offsetDateTime = dateTime.atOffset(ZoneOffset.ofHours(-6));System.out.println(offsetDateTime);//设置时区为美国时区ZonedDateTime zonedDateTime = dateTime.atZone(ZoneId.of("America/El_Salvador"));System.out.println(zonedDateTime);System.out.println(zonedDateTime.toEpochSecond());//输入LocalDateTime的工夫戳,因为LocalDateTime是不带时区的,须要指定时区System.out.println(dateTime.toEpochSecond(ZoneOffset.ofHours(0)));

Period和Duration

  • Period操作的时间跨度是年月日
public static Period of(int years, int months, int days)public static Period between(LocalDate startDateInclusive, LocalDate endDateExclusive)//获取以后Period实例的单位public List<TemporalUnit> getUnits()//获取TemporalUnit的数量public long get(TemporalUnit unit)public int getYears() public int getMonths() public int getDays() 
  • Duration操作的时间跨度是时分秒,外加纳秒
//距离days天的时间差(单位秒)public static Duration ofDays(long days)//距离hours小时的时间差(单位秒)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()//时间差的距离天数,天数单位局部,没有则是0public long toDaysPart()//时间差的小时跨度数,小时单位局部,没有则是0public int toHoursPart()//时间差的分钟跨度数,分钟单位局部,没有则是0public int toMinutesPart()//时间差的秒跨度数,秒单位分,没有则是0public int toSecondsPart()
  • 应用示例
Duration duration = Duration.ofHours(1+24);System.out.println("相隔天数:"+duration.toDaysPart());System.out.println("外加"+duration.toHoursPart()+"小时");---------------输入后果-----------------相隔天数:1外加1小时

DateTimeFormatter

//结构指定模式的工夫格局类public static DateTimeFormatter ofPattern(String pattern)//结构指定模式的工夫格局类,并指定Localepublic static DateTimeFormatter ofPattern(String pattern, Locale locale)public DateTimeFormatter withLocale(Locale locale) //解析进去的工夫是带时区的public DateTimeFormatter withZone(ZoneId zone)//获取以后时区public ZoneId getZone() public String format(TemporalAccessor temporal)//解析字符串为TemporalAccessorpublic TemporalAccessor parse(CharSequence text) 
  • 应用示例
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));---------------输入后果-----------------{InstantSeconds=1616177532},ISO,America/El_Salvador resolved to 2021-03-19T12:12:121616177532

ZoneId和ZoneOffset

  • ZoneId示意时区,会依据夏令时调整。在不同年份工夫,该ZoneId对应的ZonedDateTime会变动
public static ZoneId systemDefault()//获取jdk反对的ZoneId的汇合public static Set<String> getAvailableZoneIds()public static ZoneId of(String zoneId)//依据一个TemporalAccessor的实体获取,如:ZonedDateTimepublic static ZoneId from(TemporalAccessor temporal)
  • ZoneOffset也示意时区,固定工夫的偏移。不会依据夏令时调整,固定不变的
public static ZoneOffset of(String offsetId)public static ZoneOffset ofHours(int hours) public static ZoneOffset ofHoursMinutesSeconds(int hours, int minutes, int seconds)

ZonedDateTime和OffsetDateTime

  • ZonedDateTime,对应ZoneId加LocalDateTime的联合
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() //转化为OffsetDateTime(时区变成固定的,不再依据夏令时动静调整)public OffsetDateTime toOffsetDateTime() 
  • OffsetDateTime,对应ZoneOffset加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)//以后工夫转成offset时区示意的工夫public OffsetDateTime withOffsetSameInstant(ZoneOffset offset) 
  • ZonedDateTime和OffsetDateTime应用示例
System.out.println(LocalDateTime.now());//以后工夫并转为America/Toronto时区的工夫(带America/Toronto时区,会依据夏令时调整工夫)ZonedDateTime zonedDateTime = ZonedDateTime.ofInstant(Instant.now(), ZoneId.of("America/Toronto"));System.out.println(zonedDateTime);//以后工夫并转为+0时区的工夫OffsetDateTime offsetDateTime = OffsetDateTime.ofInstant(Instant.now(), ZoneOffset.of("+0"));System.out.println(offsetDateTime);---------------输入后果---------------------2021-01-10T15:07:08.0729682021-01-10T02:07:08.073187-05:00[America/Toronto]2021-01-10T07:07:08.075340Z

MonthDay和YearMonth

  • 月日的操作类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()//以后月的总天数public int getDayOfMonth()
  • 年月的操作类YearMonth
public static YearMonth now()public static YearMonth of(int year, int month) //依据一个工夫获取YearMonth,如果LocalDatepublic static YearMonth from(TemporalAccessor temporal)//是否平年public boolean isLeapYear()public Month getMonth()public int getYear()//以后年的总天数public int lengthOfYear()//此天数是否在这个月是无效的public boolean isValidDay(int dayOfMonth)public LocalDate atDay(int dayOfMonth)
  • 应用示例
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 是否是平年:"+yearMonth.isLeapYear());------------输入后果--------------false2021 是否是平年:false

ChronoUnit

  • 工夫度量单位,枚举类,继承TemporalUnit。它示意的是一个工夫距离用什么单位度量,比方两天的工夫距离能够用48个小时代替示意。个别用于某工夫单位的设置,加减操作
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的定义    private final String name;    private final Duration duration;    private ChronoUnit(String name, Duration estimatedDuration) {        this.name = name;        this.duration = estimatedDuration;    }}

ChronoField

  • 继承TemporalField,枚举类。和ChronoUnit性能相似,基于TemporalUnit实现,个别用于获取不同工夫域的值
public enum ChronoField implements TemporalField {    //一秒钟的纳秒数    NANO_OF_SECOND("NanoOfSecond", NANOS, SECONDS, ValueRange.of(0, 999_999_999))    //一分钟的秒数    SECOND_OF_MINUTE("SecondOfMinute", SECONDS, MINUTES, ValueRange.of(0, 59), "second")    //一个小时的分钟数    MINUTE_OF_HOUR("MinuteOfHour", MINUTES, HOURS, ValueRange.of(0, 59), "minute")    //一上午或者一下午有多少个小时    CLOCK_HOUR_OF_AMPM("ClockHourOfAmPm", HOURS, HALF_DAYS, ValueRange.of(1, 12))    //一天的小时数    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")    //以后月的天数    DAY_OF_MONTH("DayOfMonth", DAYS, MONTHS, ValueRange.of(1, 28, 31), "day")    //以后年的天数    DAY_OF_YEAR("DayOfYear", DAYS, YEARS, ValueRange.of(1, 365, 366))    //以后月的周数    ALIGNED_WEEK_OF_MONTH("AlignedWeekOfMonth", WEEKS, MONTHS, ValueRange.of(1, 4, 5))    //以后年的周数    ALIGNED_WEEK_OF_YEAR("AlignedWeekOfYear", WEEKS, YEARS, ValueRange.of(1, 53))    //以每月的第一天为星期一,而后计算当天是一周的第几天    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))    //以后年的月数    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 和 ALIGNED_DAY_OF_WEEK_IN_MONTH 应用示例
//以1号为周一,每七天一周,10号就是一周的第三天int num = LocalDateTime.now().get(ChronoField.ALIGNED_DAY_OF_WEEK_IN_MONTH);System.out.println(num);//这个月的第二周num = LocalDateTime.now().get(ChronoField.ALIGNED_WEEK_OF_MONTH);System.out.println(num);------------输入后果--------------32

工夫转换调整接口:TemporalAdjuster

  • 因为java.time的工夫类都是不可变,因而须要调整工夫时,可调用该办法实现
  • jdk提供了一些默认调整办法的工具类TemporalAdjusters
//由子类实现Temporal adjustInto(Temporal temporal)

TemporalAdjusters

  • 工夫调整工具类
//设置天单位度量数为年的第一天public static TemporalAdjuster firstDayOfYear()//设置天单位度量数为年的最初一天public static TemporalAdjuster lastDayOfYear()//设置工夫为下一年的第一天public static TemporalAdjuster firstDayOfNextYear() //设置工夫为当月的第一天public static TemporalAdjuster firstInMonth(DayOfWeek dayOfWeek)//设置工夫为当月的最初一天public static TemporalAdjuster lastInMonth(DayOfWeek dayOfWeek)//设置工夫为当月第ordinal个周的星期几-dayOfWeekpublic static TemporalAdjuster dayOfWeekInMonth(int ordinal, DayOfWeek dayOfWeek)//设置工夫为下周星期几public static TemporalAdjuster next(DayOfWeek dayOfWeek) //设置工夫为上周星期几public static TemporalAdjuster previous(DayOfWeek dayOfWeek)//如果以后星期数和dayOfWeek不一样,则设置工夫为上周的星期几-dayOfWeekpublic static TemporalAdjuster previousOrSame(DayOfWeek dayOfWeek) 
  • 示例
LocalDateTime dateTime = LocalDateTime.now();//设置天区域的值为以后月的第一天,其余域的值不变(当初工夫是202101)dateTime = dateTime.with(TemporalAdjusters.firstDayOfMonth());System.out.println(dateTime);------------输入后果--------------2021-01-01T14:50:40.659823

Date和LocalDateTime互转

  • JDK1.8之前用的工夫类是Date,为了兼容,咱们须要理解一下,Date和LocalDateTime之间的转换
  • 示例
//Date转LocalDateTimeDate 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);------------输入后果------------2021-01-10T14:25:08.6492021-01-10T14:25:08.649
//LocalDateTime转DateLocalDateTime localDateTime = LocalDateTime.now();Date date = Date.from(localDateTime.atZone(ZoneId.systemDefault()).toInstant());System.out.println(date);------------输入后果------------Sun Jan 10 14:29:04 CST 2021

欢送指注释中谬误

参考文章

  • JAVA8工夫类库与JodaTime
  • JDK8 新个性 - 新的工夫和日期 API