Java8 引入的时间处理类

Java About 2,092 words

相关类

  • Instant:代替 Date
  • DateTimeFormatter:线程安全,代替 SimpleDateFormat
  • LocalTime
  • LocalDate
  • LocalDateTime:代替 Calendar
  • Duration
  • Period
  • ChronoUnit

格式化时间

yyyyMMddyyyy-MM-dd

LocalDateTime now = LocalDateTime.now();

// BASIC_ISO_DATE yyyyMMdd
String format = now.format(DateTimeFormatter.BASIC_ISO_DATE);

// ISO_DATE yyyy-MM-dd
String format2 = now.format(DateTimeFormatter.ISO_DATE);
System.out.println("ISO_DATE#" + format2);

yyyy-MM-dd HH:mm:ss

DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

LocalDateTime now = LocalDateTime.now();
String format3 = now.format(formatter);
System.out.println("formatter#" + format3);

uuuu-MM-dd HH:mm:ss(推荐使用)

DateTimeFormatter formatter = DateTimeFormatter.ofPattern("uuuu-MM-dd HH:mm:ss");

LocalDateTime now = LocalDateTime.now();
String format4 = now.format(formatterUUUU);
System.out.println("formatterUUUU#" + format4);

Date 转 LocalDateTime

Date date = new Date();
LocalDateTime localDateTime = LocalDateTime.ofInstant(date.toInstant(), ZoneId.systemDefault());
System.out.println(localDateTime);

Date 转 Instant

Date date = new Date();
date.toInstant();

LocalDateTime 获取毫秒值

long ts = LocalDateTime.now().atZone(ZoneId.systemDefault()).toInstant().toEpochMilli();

毫秒值转 LocalDateTime

秒值转LocalDateTime可以乘以1000转成毫秒值进行转换

long millis = System.currentTimeMillis();
LocalDateTime ldt = Instant.ofEpochMilli(millis).atZone(ZoneId.systemDefault()).toLocalDateTime();

LocalDateTime 获取秒值

long second = LocalDateTime.now().atZone(ZoneId.systemDefault()).toInstant().getEpochSecond();

获取当天凌晨 LocalDateTime

LocalDateTime endOfDay = LocalDateTime.of(LocalDate.now(), LocalTime.MAX);
System.out.println(endOfDay);

获取当前时间到凌晨的毫秒值的差值

Duration

long diffMillis = Duration.between(LocalDateTime.now(), LocalDateTime.of(LocalDate.now(), LocalTime.MAX)).toMillis();
System.out.println("millis diff by Duration#" + diffMillis);

ChronoUnit

long millisDiff = ChronoUnit.MILLIS.between(LocalDateTime.now(), LocalDateTime.of(LocalDate.now(), LocalTime.MAX));
System.out.println("当前时间到今晚0点的毫秒值  ChronoUnit#" + millisDiff);

参考

stackoverflow: uuuu vs yyyy

Views: 1,986 · Posted: 2021-03-30

————        END        ————

Give me a Star, Thanks:)

https://github.com/fendoudebb/LiteNote

扫描下方二维码关注公众号和小程序↓↓↓

扫描下方二维码关注公众号和小程序↓↓↓


Today On History
Browsing Refresh