关于java:基础篇JDK8的日期处理API-必知必备

37次阅读

共计 18431 个字符,预计需要花费 47 分钟才能阅读完成。

前言

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/Shanghai
2021-01-03T05:05:31.791Z
1609650331791
  • 偏移时钟 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.088Z
2021-01-03T05:43:19.090Z
2021-01-03T05:43:19.107Z
2021-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.272Z
2021-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)
// 依据毫秒生成 Instant
public static Instant ofEpochMilli(long epochMilli)
// 依据秒生成 Instant,外附加纳秒单位的数值
public static Instant ofEpochSecond(long epochSecond, long nanoAdjustment)
//text 的格局:2021-01-04T06:37:53.743Z
public 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);
// 过来工夫和以后工夫的相差值, 能够指定单位 TemporalUnit
System.out.println(preInstant.until(Instant.now(), ChronoUnit.MINUTES));
--------------- 输入后果 ------------------------
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 的应用
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:00
2021-01-04T06:53:01.895Z
2021-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) 
//jdk9
public 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.000000001
12:12
12: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);
// 以后工夫加日期, 并设置时区为 offset
long seconds = LocalTime.now().toEpochSecond(LocalDate.now(), ZoneOffset.ofHours(-6));
System.out.println(seconds);
--------------- 输入后果 -----------------
12:12:12.000000001
2021-01-04T12:12:12.000000001
16:29:33.917387700-06:00
1609799373

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-04
2020-03-19
2021-03-19
  • LocalDate 的操作
LocalDate localDate = LocalDate.parse("20210319", DateTimeFormatter.BASIC_ISO_DATE);
System.out.println("以后年的第几天:" + localDate.getDayOfYear() + "; 以后月的第几天" + localDate.getDayOfMonth()+"; 以后星期几:"+localDate.getDayOfWeek());
// 加 LocalTime 转变为 LocalDateTime
LocalDateTime dateTime = localDate.atTime(LocalTime.now());
System.out.println(dateTime);
--------------- 输入后果 -----------------
以后年的第几天:78; 以后月的第几天 19; 以后星期几:FRIDAY
2021-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.000000001
2021-01-04T16:36:40.193887
2021-03-19T12:12:12
  • LocalDateTime 操作示例
LocalDateTime dateTime = LocalDateTime.now();
// 设置偏移时区为 -6
OffsetDateTime 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()
// 时间差的距离天数,天数单位局部,没有则是0
public long toDaysPart()
// 时间差的小时跨度数,小时单位局部,没有则是0
public int toHoursPart()
// 时间差的分钟跨度数,分钟单位局部,没有则是0
public int toMinutesPart()
// 时间差的秒跨度数,秒单位分,没有则是0
public 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)
// 结构指定模式的工夫格局类,并指定 Locale
public 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)
// 解析字符串为 TemporalAccessor
public 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:12
1616177532

ZoneId 和 ZoneOffset

  • ZoneId 示意时区,会依据夏令时调整。在不同年份工夫,该 ZoneId 对应的 ZonedDateTime 会变动
public static ZoneId systemDefault()
// 获取 jdk 反对的 ZoneId 的汇合
public static Set<String> getAvailableZoneIds()
public static ZoneId of(String zoneId)
// 依据一个 TemporalAccessor 的实体获取,如:ZonedDateTime
public 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.072968
2021-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,如果 LocalDate
public 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());
------------ 输入后果 --------------
false
2021 是否是平年: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);
------------ 输入后果 --------------
3
2

工夫转换调整接口: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 个周的星期几-dayOfWeek
public static TemporalAdjuster dayOfWeekInMonth(int ordinal, DayOfWeek dayOfWeek)
// 设置工夫为下周星期几
public static TemporalAdjuster next(DayOfWeek dayOfWeek) 
// 设置工夫为上周星期几
public static TemporalAdjuster previous(DayOfWeek dayOfWeek)
// 如果以后星期数和 dayOfWeek 不一样,则设置工夫为上周的星期几-dayOfWeek
public 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 转 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);
------------ 输入后果 ------------
2021-01-10T14:25:08.649
2021-01-10T14:25:08.649
//LocalDateTime 转 Date
LocalDateTime 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

正文完
 0