DateUtil.java 2.7 KB

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