DateUtils.java 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. package com.zsElectric.boot.common.util;
  2. import cn.hutool.core.date.DateTime;
  3. import cn.hutool.core.date.DateUtil;
  4. import cn.hutool.core.util.ReflectUtil;
  5. import cn.hutool.core.util.StrUtil;
  6. import org.springframework.format.annotation.DateTimeFormat;
  7. import java.lang.reflect.Field;
  8. /**
  9. * 日期工具类
  10. *
  11. * @author haoxr
  12. * @since 2.4.2
  13. */
  14. public class DateUtils {
  15. /**
  16. * 区间日期格式化为数据库日期格式
  17. * <p>
  18. * eg:2021-01-01 → 2021-01-01 00:00:00
  19. *
  20. * @param obj 要处理的对象
  21. * @param startTimeFieldName 起始时间字段名
  22. * @param endTimeFieldName 结束时间字段名
  23. */
  24. public static void toDatabaseFormat(Object obj, String startTimeFieldName, String endTimeFieldName) {
  25. Field startTimeField = ReflectUtil.getField(obj.getClass(), startTimeFieldName);
  26. Field endTimeField = ReflectUtil.getField(obj.getClass(), endTimeFieldName);
  27. if (startTimeField != null) {
  28. processDateTimeField(obj, startTimeField, startTimeFieldName, "yyyy-MM-dd 00:00:00");
  29. }
  30. if (endTimeField != null) {
  31. processDateTimeField(obj, endTimeField, endTimeFieldName, "yyyy-MM-dd 23:59:59");
  32. }
  33. }
  34. /**
  35. * 处理日期字段
  36. *
  37. * @param obj 要处理的对象
  38. * @param field 字段
  39. * @param fieldName 字段名
  40. * @param targetPattern 目标数据库日期格式
  41. */
  42. private static void processDateTimeField(Object obj, Field field, String fieldName, String targetPattern) {
  43. Object fieldValue = ReflectUtil.getFieldValue(obj, fieldName);
  44. if (fieldValue != null) {
  45. // 得到原始的日期格式
  46. String pattern = field.isAnnotationPresent(DateTimeFormat.class) ? field.getAnnotation(DateTimeFormat.class).pattern() : "yyyy-MM-dd";
  47. // 转换为日期对象
  48. DateTime dateTime = DateUtil.parse(StrUtil.toString(fieldValue), pattern);
  49. // 转换为目标数据库日期格式
  50. ReflectUtil.setFieldValue(obj, fieldName, dateTime.toString(targetPattern));
  51. }
  52. }
  53. }