说明
java.util.Date 包的类可修改 非线程安全
java.time 包不可修改 线程安全
目录
Instant—它代表的是时间戳
Instant now = Instant.now();
格式:2020-10-29T09:09:46.319Z
long l = Instant.now().toEpochMilli();
格式:1604025232474
LocalDate—日期
LocalDate now = LocalDate.now();
格式:2020-10-30
LocalTime—时间
LocalTime now = LocalTime.now();
格式:10:38:39.879
LocalDateTime—日期及时间
LocalDateTime now = LocalDateTime.now();
格式:2020-10-30T10:38:07.259
String format = LocalDateTime.now().format(DateTimeFormatter.ISO_LOCAL_DATE);
格式:2020-10-30
String format = LocalDateTime.now().format(DateTimeFormatter.ISO_LOCAL_TIME);
格式:10:52:51.921
String format = LocalDateTime.now().format(DateTimeFormatter.BASIC_ISO_DATE);
格式:20201030
下面的格式必须自定义(需要毫秒,自行添加大写 SSS)
String format = LocalDateTime.now().format(DateTimeFormatter.ofPattern(“yyyy-MM-dd HH:mm:ss”));
格式:2020-10-30 11:03:36
字符串转时间(需要毫秒,自行添加大写 SSS)
DateTimeFormatter formatter = DateTimeFormatter.ofPattern(“yyyy-MM-dd HH:mm:ss”);
LocalDateTime parse = LocalDateTime.parse(“2020-12-12 12:12:12”,formatter);
格式:2020-12-12T12:12:12
获取指定时间
LocalDateTime of = LocalDateTime.of(2020, 12, 12, 12, 12, 12);
格式:2020-12-12T12:12:12
ZonedDateTime—包含时区的完整的日期时间
ZonedDateTime now = ZonedDateTime.now();
格式:2020-10-30T10:39:14.395+08:00[Asia/Shanghai]
Period—两个日期之间相差的天数
不建议使用(只会计算月内相差,超过一月会计算失败)
LocalDate of = LocalDate.of(2020, 12, 12);
LocalDate now = LocalDate.now();// 2020-10-30
Period between = Period.between(of, now);
System.out.println(between.getMonths());// -1
Druation—两个日期时间之间间隔的秒和纳秒
建议使用
LocalDateTime of = LocalDateTime.of(2020, 12, 12,12,12,12);
LocalDateTime now = LocalDateTime.now();// 2020-10-30T14:34:15.980
Duration between = Duration.between(of, now);
System.out.println(between.toDays());// -42
单独获取年月日时分秒毫秒
LocalDate now = LocalDate.now();
int year = now.getYear();
int monthValue = now.getMonthValue();
int dayOfMonth = now.getDayOfMonth();
int dayOfYear = now.getDayOfYear();
System.out.println(now); 2020-10-30
System.out.println(year); 2020
System.out.println(monthValue); 10
System.out.println(dayOfMonth); 30
System.out.println(dayOfYear); 304
LocalTime now1 = LocalTime.now();
int hour = now1.getHour();
int minute = now1.getMinute();
int second = now1.getSecond();
int nano = now1.getNano();
System.out.println(now1); 11:24:17.908
System.out.println(hour); 11
System.out.println(minute); 24
System.out.println(second); 17
System.out.println(nano); 908000000
加时间
LocalDateTime now = LocalDateTime.now();
System.out.println(now);
System.out.println(now.plusYears(12));
System.out.println(now.plusMonths(12));
System.out.println(now.plusDays(12));
System.out.println(now.plusWeeks(12));
System.out.println(now.plusHours(12));
System.out.println(now.plusMinutes(12));
System.out.println(now.plusSeconds(12));
System.out.println(now.plusNanos(12));
结果:
2032-10-30T14:50:24.656
2021-10-30T14:50:24.656
2020-11-11T14:50:24.656
2021-01-22T14:50:24.656
2020-10-31T02:50:24.656
2020-10-30T15:02:24.656
2020-10-30T14:50:36.656
2020-10-30T14:50:24.656000012