看过易忘,留下备查
jdk8中对时间的获取方式进行了新的修改,常用的获取时间的方式为:
1: LocalDate.now()
2: LocalTime.now(),
3: LocalDateTime.now() ,
格式化时间:DateTimeFormatter.ofPattern();
获取当前时间戳有两种方式,本质上还是通过Instant获取:
1:LocalDateTime.now().toInstant(ZoneOffset.of("+8")).toEpochMill();
2:Instant.now().toEpochMill()
// 获取日期 和 时间 及格式化
LocalDate localDate = LocalDate.now();
LocalTime localTime = LocalTime.now();
LocalDateTime localDateTime = LocalDateTime.now();
String formatDateTime1 = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss").format(localDateTime);
String formatDateTime2 = localDateTime.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
System.out.println("localDate: " + localDate + "\n");
System.out.println("localTime: " + localTime + "\n");
System.out.println("localDateTime: " + localDateTime + "\n");
System.out.println("formatDateTime1: " + formatDateTime1 + "\n");
System.out.println("formatDateTime2: " + formatDateTime2 + "\n");
// 获取秒值及毫秒值
long epochSecond = LocalDateTime.now().toInstant(ZoneOffset.of("+8")).getEpochSecond();
long milliSecond = LocalDateTime.now().toInstant(ZoneOffset.of("+8")).toEpochMilli();
long milliSeconds = Instant.now().toEpochMilli();
long epochSeconds = Instant.now().getEpochSecond();
System.out.println("epochSecond: " + epochSecond + "\n");
System.out.println("milliSecond: " + milliSecond + "\n");
System.out.println("epochSeconds: " + epochSeconds + "\n");
System.out.println("milliSeconds: " + milliSeconds + "\n");
// Date 与 LocalDateTime 及 String 之间的转换
LocalDateTime dateToLocalDateTime = new Date().toInstant().atZone(ZoneId.of("+8")).toLocalDateTime();
LocalDateTime parseToLocalDateTime = LocalDateTime.parse(formatDateTime1, DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
Date localDateTimeToDate = Date.from(LocalDateTime.now().toInstant(ZoneOffset.of("+8")));
System.out.println("dateToLocalDateTime: " + dateToLocalDateTime + "\n");
System.out.println("parseToLocalDateTime: " + parseToLocalDateTime + "\n");
System.out.println("localDateTimeToDate: " + localDateTimeToDate + "\n");