DateUtils.java 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. package com.alvin.common.util;
  2. import org.springframework.util.Assert;
  3. import java.time.*;
  4. import java.time.format.DateTimeFormatter;
  5. import java.time.temporal.TemporalAdjusters;
  6. /**
  7. * 日期工具类
  8. * 日期大小比较
  9. * 日期加减
  10. * 时间戳转换
  11. *
  12. * @author tianyunperfect
  13. * @date 2020/05/28
  14. */
  15. public class DateUtils {
  16. /**
  17. * 当前秒
  18. *
  19. * @return {@link Long}
  20. */
  21. public static Long getEpochMilli() {
  22. return Instant.now().toEpochMilli();
  23. }
  24. /**
  25. * 当前秒
  26. *
  27. * @return {@link Long}
  28. */
  29. public static Long getEpochSecond() {
  30. return Instant.now().getEpochSecond();
  31. }
  32. /**
  33. * 将Long类型的时间戳转换成String 类型的时间格式,时间格式为:yyyy-MM-dd HH:mm:ss
  34. */
  35. public static String convertTimeToString(Long time) {
  36. Assert.notNull(time, "time is null");
  37. DateTimeFormatter ftf = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
  38. return ftf.format(LocalDateTime.ofInstant(Instant.ofEpochMilli(time), ZoneId.systemDefault()));
  39. }
  40. /**
  41. * 将字符串转日期成Long类型的时间戳,格式为:yyyy-MM-dd HH:mm:ss
  42. */
  43. public static Long convertTimeToLong(String time) {
  44. Assert.notNull(time, "time is null");
  45. DateTimeFormatter ftf = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
  46. LocalDateTime parse = LocalDateTime.parse("2018-05-29 13:52:50", ftf);
  47. return LocalDateTime.from(parse).atZone(ZoneId.systemDefault()).toInstant().toEpochMilli();
  48. }
  49. /**
  50. * 取本月第一天
  51. */
  52. public static LocalDate firstDayOfThisMonth() {
  53. LocalDate today = LocalDate.now();
  54. return today.with(TemporalAdjusters.firstDayOfMonth());
  55. }
  56. /**
  57. * 取本月第N天
  58. */
  59. public static LocalDate dayOfThisMonth(int n) {
  60. LocalDate today = LocalDate.now();
  61. return today.withDayOfMonth(n);
  62. }
  63. /**
  64. * 取本月最后一天
  65. */
  66. public static LocalDate lastDayOfThisMonth() {
  67. LocalDate today = LocalDate.now();
  68. return today.with(TemporalAdjusters.lastDayOfMonth());
  69. }
  70. /**
  71. * 取本月第一天的开始时间
  72. */
  73. public static LocalDateTime startOfThisMonth() {
  74. return LocalDateTime.of(firstDayOfThisMonth(), LocalTime.MIN);
  75. }
  76. /**
  77. * 取本月最后一天的结束时间
  78. */
  79. public static LocalDateTime endOfThisMonth() {
  80. return LocalDateTime.of(lastDayOfThisMonth(), LocalTime.MAX);
  81. }
  82. }