DateUtils.java 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940
  1. package com.crm.manager.util;
  2. import java.time.Instant;
  3. import java.time.LocalDateTime;
  4. import java.time.ZoneId;
  5. import java.time.format.DateTimeFormatter;
  6. import java.util.Date;
  7. public class DateUtils {
  8. /**
  9. * Date 转 秒级时间戳(数据库存的就是这个)
  10. */
  11. public static long dateToSecondTimestamp(Date date) {
  12. if (date == null) {
  13. return 0;
  14. }
  15. return date.getTime() / 1000; // 毫秒 → 秒(关键)
  16. }
  17. // 常用格式:yyyy-MM-dd HH:mm:ss
  18. public static final DateTimeFormatter FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
  19. /**
  20. * 秒级时间戳 → 日期字符串
  21. * @param secondTimestamp 秒级时间戳 (如 1735458266)
  22. * @return yyyy-MM-dd HH:mm:ss
  23. */
  24. public static String secondToDateTimeStr(long secondTimestamp) {
  25. if (secondTimestamp <= 0) {
  26. return null;
  27. }
  28. // 秒级时间戳转 Instant
  29. Instant instant = Instant.ofEpochSecond(secondTimestamp);
  30. // 转东八区时间(中国时区)
  31. LocalDateTime localDateTime = LocalDateTime.ofInstant(instant, ZoneId.of("Asia/Shanghai"));
  32. // 格式化字符串
  33. return localDateTime.format(FORMATTER);
  34. }
  35. }