DateUtils.java 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344
  1. package com.ruoyi.common.utils;
  2. import java.lang.management.ManagementFactory;
  3. import java.text.ParseException;
  4. import java.text.SimpleDateFormat;
  5. import java.time.*;
  6. import java.time.format.DateTimeFormatter;
  7. import java.time.format.DateTimeParseException;
  8. import java.time.temporal.TemporalAdjusters;
  9. import java.util.ArrayList;
  10. import java.util.Calendar;
  11. import java.util.Date;
  12. import java.util.List;
  13. import org.apache.commons.lang3.time.DateFormatUtils;
  14. /**
  15. * 时间工具类
  16. *
  17. * @author ruoyi
  18. */
  19. public class DateUtils extends org.apache.commons.lang3.time.DateUtils {
  20. public static String YYYY = "yyyy";
  21. public static String YYYY_MM = "yyyy-MM";
  22. public static String YYYY_MM_DD = "yyyy-MM-dd";
  23. public static String YYYYMMDDHHMMSS = "yyyyMMddHHmmss";
  24. public static String YYYY_MM_DD_HH_MM_SS = "yyyy-MM-dd HH:mm:ss";
  25. public static String YYYYMMDD = "yyyyMMdd";
  26. private static String[] parsePatterns = {
  27. "yyyy-MM-dd", "yyyy-MM-dd HH:mm:ss", "yyyy-MM-dd HH:mm", "yyyy-MM",
  28. "yyyy/MM/dd", "yyyy/MM/dd HH:mm:ss", "yyyy/MM/dd HH:mm", "yyyy/MM",
  29. "yyyy.MM.dd", "yyyy.MM.dd HH:mm:ss", "yyyy.MM.dd HH:mm", "yyyy.MM"};
  30. public static String getDateNow() {
  31. return dateTimeNow(YYYYMMDD);
  32. }
  33. /**
  34. * 获取当前Date型日期
  35. *
  36. * @return Date() 当前日期
  37. */
  38. public static Date getNowDate() {
  39. return new Date();
  40. }
  41. /**
  42. * 获取当前日期, 默认格式为yyyy-MM-dd
  43. *
  44. * @return String
  45. */
  46. public static String getDate() {
  47. return dateTimeNow(YYYY_MM_DD);
  48. }
  49. public static String getYear() {
  50. return dateTimeNow(YYYY);
  51. }
  52. public static final String getTime() {
  53. return dateTimeNow(YYYY_MM_DD_HH_MM_SS);
  54. }
  55. public static final String dateTimeNow() {
  56. return dateTimeNow(YYYYMMDDHHMMSS);
  57. }
  58. public static final String dateTimeNow(final String format) {
  59. return parseDateToStr(format, new Date());
  60. }
  61. public static final String dateTime(final Date date) {
  62. return parseDateToStr(YYYY_MM_DD, date);
  63. }
  64. public static final String parseDateToStr(final String format, final Date date) {
  65. return new SimpleDateFormat(format).format(date);
  66. }
  67. public static final Date dateTime(final String format, final String ts) {
  68. try {
  69. return new SimpleDateFormat(format).parse(ts);
  70. } catch (ParseException e) {
  71. throw new RuntimeException(e);
  72. }
  73. }
  74. /**
  75. * 日期路径 即年/月/日 如2018/08/08
  76. */
  77. public static final String datePath() {
  78. Date now = new Date();
  79. return DateFormatUtils.format(now, "yyyy/MM/dd");
  80. }
  81. /**
  82. * 日期路径 即年/月/日 如20180808
  83. */
  84. public static final String dateTime() {
  85. Date now = new Date();
  86. return DateFormatUtils.format(now, "yyyyMMdd");
  87. }
  88. /**
  89. * 日期型字符串转化为日期 格式
  90. */
  91. public static Date parseDate(Object str) {
  92. if (str == null) {
  93. return null;
  94. }
  95. try {
  96. return parseDate(str.toString(), parsePatterns);
  97. } catch (ParseException e) {
  98. return null;
  99. }
  100. }
  101. /**
  102. * 将字符串转换为Date对象(支持多种格式)
  103. * @param dateString 日期字符串
  104. * @return 对应的Date对象,解析失败返回null
  105. */
  106. public static Date convertStringToDate(String dateString) {
  107. // 定义可能的日期格式(按优先级排序)
  108. for (String pattern : parsePatterns) {
  109. try {
  110. DateTimeFormatter formatter = DateTimeFormatter.ofPattern(pattern);
  111. LocalDate localDate = LocalDate.parse(dateString, formatter);
  112. return Date.from(localDate.atStartOfDay(ZoneId.systemDefault()).toInstant());
  113. } catch (DateTimeParseException e) {
  114. // 尝试下一个格式
  115. }
  116. }
  117. return null; // 所有格式都尝试失败
  118. }
  119. /**
  120. * 获取服务器启动时间
  121. */
  122. public static Date getServerStartDate() {
  123. long time = ManagementFactory.getRuntimeMXBean().getStartTime();
  124. return new Date(time);
  125. }
  126. /**
  127. * 计算相差天数
  128. */
  129. public static int differentDaysByMillisecond(Date date1, Date date2) {
  130. return Math.abs((int) ((date2.getTime() - date1.getTime()) / (1000 * 3600 * 24)));
  131. }
  132. /**
  133. * 计算两个时间差
  134. */
  135. public static String getDatePoor(Date endDate, Date nowDate) {
  136. long nd = 1000 * 24 * 60 * 60;
  137. long nh = 1000 * 60 * 60;
  138. long nm = 1000 * 60;
  139. // long ns = 1000;
  140. // 获得两个时间的毫秒时间差异
  141. long diff = endDate.getTime() - nowDate.getTime();
  142. // 计算差多少天
  143. long day = diff / nd;
  144. // 计算差多少小时
  145. long hour = diff % nd / nh;
  146. // 计算差多少分钟
  147. long min = diff % nd % nh / nm;
  148. // 计算差多少秒//输出结果
  149. // long sec = diff % nd % nh % nm / ns;
  150. return day + "天" + hour + "小时" + min + "分钟";
  151. }
  152. /**
  153. * 增加 LocalDateTime ==> Date
  154. */
  155. public static Date toDate(LocalDateTime temporalAccessor) {
  156. ZonedDateTime zdt = temporalAccessor.atZone(ZoneId.systemDefault());
  157. return Date.from(zdt.toInstant());
  158. }
  159. /**
  160. * 增加 LocalDate ==> Date
  161. */
  162. public static Date toDate(LocalDate temporalAccessor) {
  163. LocalDateTime localDateTime = LocalDateTime.of(temporalAccessor, LocalTime.of(0, 0, 0));
  164. ZonedDateTime zdt = localDateTime.atZone(ZoneId.systemDefault());
  165. return Date.from(zdt.toInstant());
  166. }
  167. /**
  168. * 根据时间加减时间(时间可为负)
  169. *
  170. * @param dateTime 时间
  171. * @param seconds 加减的天数
  172. * @param format 日期格式(与dateTime格式一致)
  173. * @return
  174. */
  175. public static String plusSeconds(String dateTime, int seconds, String format) {
  176. //LocalDateTime parse = parse(dateTime, format);
  177. //LocalDateTime localDateTime = parse.plusMinutes(seconds);
  178. LocalDate parse = LocalDate.parse(dateTime);
  179. LocalDate localDate = LocalDate.now().plusDays(seconds);
  180. String date = localDate.format(DateTimeFormatter.ofPattern(format));
  181. return date;
  182. }
  183. /***
  184. * 判断某一个日期是星期几
  185. * @param datetime
  186. * @return
  187. */
  188. public static String dateToWeek(String datetime) {
  189. SimpleDateFormat f = new SimpleDateFormat("yyyy-MM-dd");
  190. String[] weekDays = {"0", "1", "2", "3",
  191. "4", "5", "6"};
  192. Calendar cal = Calendar.getInstance(); // 获得一个日历
  193. Date datet = null;
  194. try {
  195. datet = f.parse(datetime);
  196. cal.setTime(datet);
  197. } catch (ParseException e) {
  198. e.printStackTrace();
  199. }
  200. int w = cal.get(Calendar.DAY_OF_WEEK) - 1; // 指示一个星期中的某天。
  201. if (w < 0)
  202. w = 0;
  203. return weekDays[w];
  204. }
  205. /***
  206. * 获取传入日期的前一天日期
  207. * @param dateTime
  208. * @return
  209. */
  210. public static String getYesterday(String dateTime) {
  211. SimpleDateFormat sdf = new SimpleDateFormat(YYYY_MM_DD);
  212. Date date = null;
  213. try {
  214. date = sdf.parse(dateTime);
  215. } catch (ParseException e) {
  216. throw new RuntimeException(e);
  217. }
  218. // 往前一天
  219. Calendar calendar = Calendar.getInstance();
  220. calendar.setTime(date);
  221. calendar.add(Calendar.DATE, -1);
  222. Date dateMinusOneDay = calendar.getTime();
  223. String dateMinusOneDayStr = sdf.format(dateMinusOneDay);
  224. System.out.println("往前一天的日期: " + dateMinusOneDayStr);
  225. return dateMinusOneDayStr;
  226. }
  227. /**
  228. * 获取指定月份的最后一天日期(格式为yyyy-MM-dd)
  229. *
  230. * @param year 年份(如2023)
  231. * @param month 月份(1-12)
  232. * @return 最后一天日期字符串(如"2023-02-28")
  233. * @throws IllegalArgumentException 如果月份不在1-12范围内
  234. */
  235. public static String getLastDayOfMonth(int year, int month) {
  236. // 验证月份是否有效
  237. if (month < 1 || month > 12) {
  238. throw new IllegalArgumentException("月份必须在1-12之间");
  239. }
  240. // 使用YearMonth获取月份的最后一天并格式化为字符串
  241. return YearMonth.of(year, month)
  242. .atEndOfMonth()
  243. .format(DateTimeFormatter.ISO_DATE);
  244. }
  245. /**
  246. * 判断目标日期是否在[startDate, endDate]区间内(包含边界)
  247. *
  248. * @param target 目标日期 (Date类型)
  249. * @param start 开始日期 (Date类型)
  250. * @param end 结束日期 (Date类型)
  251. * @return 若target在[start, end]区间内返回true,否则返回false
  252. */
  253. public static boolean isDateBetween(Date target, Date start, Date end) {
  254. // 转换为LocalDate(忽略时间部分)
  255. LocalDate targetDate = convertToLocalDate(target);
  256. LocalDate startDate = convertToLocalDate(start);
  257. LocalDate endDate = convertToLocalDate(end);
  258. // 判断日期区间(包含边界)
  259. return (targetDate.isEqual(startDate) || targetDate.isAfter(startDate))
  260. && (targetDate.isEqual(endDate) || targetDate.isBefore(endDate));
  261. }
  262. /**
  263. * 将Date转换为LocalDate(格式化为yyyy-MM-dd)
  264. */
  265. private static LocalDate convertToLocalDate(Date date) {
  266. return date.toInstant()
  267. .atZone(ZoneId.systemDefault())
  268. .toLocalDate();
  269. }
  270. /**
  271. * 获取当期月份,只要月份,不要年
  272. */
  273. public static String justMonth() {
  274. // 获取当前月份数字
  275. int monthNumber = LocalDate.now().getMonthValue();
  276. // 获取带前导零的月份字符串
  277. String monthPadded = String.format("%02d", monthNumber);
  278. return monthPadded;
  279. }
  280. /**
  281. * 获取本周周一至周六的日期字符串列表(格式:yyyy-MM-dd)
  282. * @return 包含6个日期字符串的List
  283. */
  284. public static List<String> getWeekDatesFromMondayToSaturday() {
  285. List<String> dates = new ArrayList<>(6);
  286. DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
  287. // 获取本周周一(如果今天是周一则返回今天)
  288. LocalDate monday = LocalDate.now()
  289. .with(TemporalAdjusters.previousOrSame(DayOfWeek.MONDAY));
  290. // 添加周一到周六的日期字符串
  291. for (int i = 0; i < 6; i++) {
  292. dates.add(monday.plusDays(i).format(formatter));
  293. }
  294. return dates;
  295. }
  296. }