package com.company;
import java.time.*;
import java.time.format.DateTimeFormatter;
import java.util.Optional;
public class Test {
public static void main(String[] args) {
//LocalDateTime使用
LocalDateTime now = LocalDateTime.now();
System.out.println(now);//2019-08-11T10:50:47.761302
System.out.println(now.getYear()+":"+now.getMonthValue()+":"+now.getDayOfMonth());//2019:8:11
LocalDateTime localDateTime = now.plusDays(10);
System.out.println(localDateTime);//2019-08-21T10:50:47.761302
LocalDateTime localDateTime1 = localDateTime.minusYears(9);
System.out.println(localDateTime1);//2010-08-21T10:50:47.761302
//手动创建一个LocalDateTime
LocalDateTime date2 = LocalDateTime.of(2017, 12, 17, 9, 31, 31, 31);
System.out.println(date2);
// Duration:计算两个时间之间的间隔
// Period:计算两个日期之间的间隔
Instant ins1 = Instant.now();
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
Instant ins2 = Instant.now();
Duration dura = Duration.between(ins1, ins2);
/**
* PT1.00023S
* 1000
*/
System.out.println(dura);
System.out.println(dura.toMillis());
System.out.println("======================");
LocalTime localTime = LocalTime.now();
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
LocalTime localTime2 = LocalTime.now();
Duration du2 = Duration.between(localTime, localTime2);
/**
* PT1.002969S
* 1002
*/
System.out.println(du2);
System.out.println(du2.toMillis());
LocalDate localDate =LocalDate.now();
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
LocalDate localDate2 = LocalDate.of(2016,12,12);
Period pe = Period.between(localDate, localDate2);
System.out.println(pe);
LocalDateTime now2 = LocalDateTime.now(ZoneId.of("Asia/Shanghai"));
System.out.println(now2);
LocalDateTime now3 = LocalDateTime.now();
ZonedDateTime zdt = now3.atZone(ZoneId.of("Asia/Shanghai"));
System.out.println(zdt);
//时间戳
//转化为时间戳 毫秒值
long time1 = LocalDateTime.now().toInstant(ZoneOffset.of("+8")).toEpochMilli();
long time2 = System.currentTimeMillis();
System.out.println(time1+"+++"+time2);
//时间戳转化为localdatetime
DateTimeFormatter df= DateTimeFormatter.ofPattern("YYYY-MM-dd HH:mm:ss.SSS");
System.out.println(df.format(LocalDateTime.ofInstant(Instant.ofEpochMilli(time1),ZoneId.of("Asia/Shanghai"))));
}
}
JDK1.8的LocalDateTime
最新推荐文章于 2022-03-30 12:30:36 发布