1、LocalDateTime获取毫秒数

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

2、Date与LocalDateTime互转

  1. //将java.util.Date 转换为java8 的java.time.LocalDateTime,默认时区为东8区
  2. public static LocalDateTime dateConvertToLocalDateTime(Date date) {
  3. return date.toInstant().atOffset(ZoneOffset.of("+8")).toLocalDateTime();
  4. }
  5. //将java8 的 java.time.LocalDateTime 转换为 java.util.Date,默认时区为东8区
  6. public static Date localDateTimeConvertToDate(LocalDateTime localDateTime) {
  7. return Date.from(localDateTime.toInstant(ZoneOffset.of("+8")));
  8. }

3、将LocalDateTime转为自定义的时间格式的字符串

  1. // DateTimeFormatter.ISO_DATE相当于DateTimeFormatter.ofPattern("yyyy-MM-dd")
  2. // 还有DateTimeFormatter.ISO_DATE_TIME
  3. // DateTimeFormatter.ISO_TIME
  4. String format = LocalDateTime.now().format(DateTimeFormatter.ISO_DATE);
  5. public static String getDateTimeAsString(LocalDateTime localDateTime, String format) {
  6. DateTimeFormatter formatter = DateTimeFormatter.ofPattern(format);
  7. return localDateTime.format(formatter);
  8. }

4、将某时间字符串转为自定义时间格式的LocalDateTime

  1. // DateTimeFormatter.ISO_DATE相当于DateTimeFormatter.ofPattern("yyyy-MM-dd")
  2. // 还有DateTimeFormatter.ISO_DATE_TIME
  3. // DateTimeFormatter.ISO_TIME
  4. String format = LocalDateTime.now().format(DateTimeFormatter.ISO_DATE);
  5. public static LocalDateTime parseStringToDateTime(String time, String format) {
  6.   DateTimeFormatter df = DateTimeFormatter.ofPattern(format);
  7.   return LocalDateTime.parse(time, df);
  8. }

5、将long类型的timestamp转为LocalDateTime

  1. public static LocalDateTime getDateTimeOfTimestamp(long timestamp) {
  2.   Instant instant = Instant.ofEpochMilli(timestamp);
  3.   ZoneId zone = ZoneId.systemDefault();
  4.   return LocalDateTime.ofInstant(instant, zone);
  5. }

6、将LocalDateTime转为long类型的timestamp

  1. public static long getTimestampOfDateTime(LocalDateTime localDateTime) {
  2.   ZoneId zone = ZoneId.systemDefault();
  3.   Instant instant = localDateTime.atZone(zone).toInstant();
  4.   return instant.toEpochMilli();
  5. }