Java JDK8新增时间相关类

161 阅读3分钟

JDK8新增时间相关类

为什么要学JDK8新增时间相关类呢

  • 代码层面
    • JDK7:代码麻烦,需要先获取毫秒值再进行比较
    • JDK8:有提供进行判断的方法和计算时间间隔的方法
  • 安全层面
    • JDK7:多线程环境下会导致数据安全的问题
    • JDK8:时间日期都是不可变的,解决了这个问题

Date类

ZoneId 时区

方法名说明
static Set getAvailableZoneIds()获取Java中支持的所有时区
static ZoneId systemDefault()获取系统默认时区对象
static ZoneId of(String zoneId)获取一个指定时区对象

Instant 时间戳

方法名说明
static Instant now()获取当前时间的Instant对象(标准时间)
static Instant ofEpochSecond(long epochSecond)根据秒获取Instant对象
static Instant ofEpochMilli(long epochMilli)根据毫秒获取Instant对象
static Instant ofEpochSecond(long epochSecond, long nanoAdjustment)根据秒和纳秒获取Instant对象
ZonedDateTime atZone(ZoneId zone)指定时区
boolean isBefore(Instant otherInstant)判断是否在参数时间之前
boolean isAfter(Instant otherInstant)判断是否在参数时间之后
Instant minusSeconds(long secondsToSubtract)减少秒
Instant minusMillis(long millisToSubtract)减少毫秒
Instant minusNanos(long nanosToSubtract)减少纳秒
Instant plusSeconds(long secondsToSubtract)增加秒
Instant plusMillis(long millisToSubtract)增加毫秒
Instant plusNanos(long nanosToSubtract)增加纳秒

+++++++

ZoneDateTime 带时区的时间

方法名说明
static ZonedDateTime now()获取当前时间的ZoneDateTime对象(带时区)
static ZoneDateTime ofXxx(....)获取指定时间的ZoneDateTime对象
ZoneDateTime withXxx(时间)修改时间系列的方法
ZoneDateTime minusXxx(时间)减少时间系列的方法
ZoneDateTime plusXxx(时间)增加时间系列的方法
  • static ZoneDateTime ofXxx(....)
    • 通过年月日分秒纳秒时区方式指定
      • of(year, month, dayOfMonth, hour, minute, second, nanoOfSecond, 时区对象)
    • 通过Instant + 时区的方式获取
      • ofInstant(Instant instant, ZoneId zoneId)
  • JDK8新增的时间对象都是不可变的,如果我们修改了,减少了,增加了时间,那么调用者是不会发生改变的,而是产生一个新的时间

日期格式化类

DateTimeFormatter

  • 用于时间的格式化和解析
方法名说明
static DateTimeFormatter ofPattern(格式)获取格式对象
String format(时间对象)按照指定方式格式化

日历类

LocalDate 年月日

LocalTime 时分秒

LocalDateTime 年月日时分秒

方法名说明
static XXX now()获取当前时间的对象
static XXX of(...)获取指定时间的对象
get开头的方法获取日历中的年月日时分秒等信息
isBefore,isAfter比较两个LocalDate
with开头的修改时间系列的方法
minus开头的减少时间系列的方法
plus开头的增加时间系列的方法
public LocalDate toLocalDate()LocalDateTime转换成一个LocalDate对象
public LocalTime toLocalTime()LocalDateTime转换成一个LocalTime对象
public boolean isLeapYear(...)判断是否为闰年

工具类

Duration 时间间隔(秒,纳秒)

方法名说明
static Duration between(Temporal startInclusive, Temporal endExclusive)获取一个对象表示两个时间对象之间的持续时间
public long toDays()获取此持续时间的天数
public long toHours()获取此持续时间内的小时数
public long toMillis()获取此持续时间内的毫秒数
public long toMinutes()获取此持续时间的分钟数
public long toNanos()获取此持续时间纳秒数

Period 时间间隔(年,月,日)

方法名说明
static Period between(LocalDate startDateInclusive, LocalDate endDateExclusive)获取两段时间的时间间隔对象
public int getDays()获取此期间的天数
public int getMonths()获取此期间的月数
public int getYears()获取此期间的年数
public long toTotalMonths()获取此期间的总月数

ChronoUnit 时间间隔(所有单位)

方法名说明
public long between(Temporal temporal1Inclusive, Tempporal temporal2Inclusive)计算两个时间对象之间的时间量
  • 在调用该方法时,一般使用long timeBetween = ChronoUnit.枚举常量.bteween(...)来计算,其中的枚举常量表示单位
枚举常量说明
NANOS纳秒
MICROS微秒
MILLIS毫秒
SECONDS
MINUTES分钟
HOURS小时
HALF_DAYS半天
DAYS
WEEKS
MONTHS
YEARS
DECADES十年
CENTURIES百年,一个世纪
MILLENNIA千年
EARA纪元
FOREVER代表永恒概念的人造单位,无限