DateUtils.java 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. package cn.iocoder.dashboard.util.date;
  2. import java.time.Duration;
  3. import java.util.Calendar;
  4. import java.util.Date;
  5. /**
  6. * 时间工具类
  7. */
  8. public class DateUtils {
  9. /**
  10. * 时区 - 默认
  11. */
  12. public static final String TIME_ZONE_DEFAULT = "GMT+8";
  13. public static final String FORMAT_YEAR_MONTH_DAY_HOUR_MINUTE_SECOND = "yyyy-MM-dd HH:mm:ss";
  14. public static Date addTime(Duration duration) {
  15. return new Date(System.currentTimeMillis() + duration.toMillis());
  16. }
  17. public static boolean isExpired(Date time) {
  18. return System.currentTimeMillis() > time.getTime();
  19. }
  20. public static long diff(Date endTime, Date startTime) {
  21. return endTime.getTime() - startTime.getTime();
  22. }
  23. /**
  24. * 创建指定时间
  25. *
  26. * @param year 年
  27. * @param mouth 月
  28. * @param day 日
  29. * @return 指定时间
  30. */
  31. public static Date buildTime(int year, int mouth, int day) {
  32. return buildTime(year, mouth, day, 0, 0, 0);
  33. }
  34. /**
  35. * 创建指定时间
  36. *
  37. * @param year 年
  38. * @param mouth 月
  39. * @param day 日
  40. * @param hour 小时
  41. * @param minute 分钟
  42. * @param second 秒
  43. * @return 指定时间
  44. */
  45. public static Date buildTime(int year, int mouth, int day,
  46. int hour, int minute, int second) {
  47. Calendar calendar = Calendar.getInstance();
  48. calendar.set(Calendar.YEAR, year);
  49. calendar.set(Calendar.MONTH, mouth - 1);
  50. calendar.set(Calendar.DAY_OF_MONTH, day);
  51. calendar.set(Calendar.HOUR_OF_DAY, hour);
  52. calendar.set(Calendar.MINUTE, minute);
  53. calendar.set(Calendar.SECOND, second);
  54. calendar.set(Calendar.MILLISECOND, 0); // 一般情况下,都是 0 毫秒
  55. return calendar.getTime();
  56. }
  57. public static Date max(Date a, Date b) {
  58. if (a == null) {
  59. return b;
  60. }
  61. if (b == null) {
  62. return a;
  63. }
  64. return a.compareTo(b) > 0 ? a : b;
  65. }
  66. }