java日期格式化

ZonedDateTime 的创建

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
//  创建时区日期时间
ZonedDateTime zonedDateTime = ZonedDateTime.of(2018, 01, 01, 0, 0, 0, 0, ZoneId.of("UTC"));
// 获取当前时间的时区时间
ZonedDateTime zonedDateTimeNow = ZonedDateTime.now(ZoneId.of("UTC"));

//使用LocalDateTime创建时区时间
LocalDateTime localDateTime = LocalDateTime.now();
// 世界标准时间时区
ZonedDateTime zonedDateTime = ZonedDateTime.of(localDateTime, ZoneId.of("UTC"));
// 获取系统时区
ZonedDateTime zonedDateTime = ZonedDateTime.now(ZoneId.systemDefault());
//获取上海时区
ZonedDateTime zonedDateTime = ZonedDateTime.now(ZoneId.of("Asia/Shanghai"));

使用ZonedDateTime格式化日期转String

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
//  可以使用Z或者X来表示时间偏移量
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss Z");
//2018-11-23 08:52:18 +0800
String formattedString = zonedDateTime.format(formatter);


// 你可以使用小写z表示时区名称
DateTimeFormatter formatter2 = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss z");
//2018-11-23 08:53:15 CST
String formattedString2 = zonedDateTime.format(formatter2);

将String转换成日期对象

两步走

  1. 将String转LocalDateTime
  2. 将LocalDateTime转ZonedDateTime
1
2
3
4
5
6
7
 ZonedDateTime zonedDateTime = LocalDateTime.parse("2018-12-03T10:15:30",DateTimeFormatter.ISO_DATE_TIME)
                .atZone(ZoneId.systemDefault());

//2018-12-03T10:15:30+08:00[Asia/Shanghai]
System.out.println(zonedDateTime.format(DateTimeFormatter.ISO_ZONED_DATE_TIME));
//2018-12-03
System.out.println(zonedDateTime.format(DateTimeFormatter.ISO_LOCAL_DATE));

Date 转 LocalDate

1
LocalDateTime localDateTime = new Date().toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime();

LocalDate转Date

1
2
 Instant instant = LocalDateTime.now().atZone(ZoneId.systemDefault()).toInstant();
 Date date = Date.from(instant);

当前时间之后的时间

1
2
3
Instant now = Instant.now();
Long expiresInMin = 30L;
Date expiresIn = Date.from(now.plus(expiresInMin, ChronoUnit.MINUTES));

LocalDateTime 转时间搓

1
2
3
4
//获取秒数
Long second = LocalDateTime.now().toEpochSecond(ZoneOffset.of("+8"));
//获取毫秒数
Long milliSecond = LocalDateTime.now().toInstant(ZoneOffset.of("+8")).toEpochMilli();

时间搓转LocalDateTime

1
2
3
Instant instant = Instant.ofEpochMilli(timestamp);
    ZoneId zone = ZoneId.systemDefault();
    return LocalDateTime.ofInstant(instant, zone);

LocalDate转时间戳

1
2
3
LocalDate localDate = LocalDate.now();
// 毫秒
long timestamp = localDate.atStartOfDay(ZoneId.systemDefault()).toInstant().toEpochMilli();