DateUtils.java 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562
  1. package com.zhongzheng.common.utils;
  2. import cn.hutool.core.lang.Validator;
  3. import org.apache.commons.lang3.RandomStringUtils;
  4. import org.apache.commons.lang3.time.DateFormatUtils;
  5. import java.lang.management.ManagementFactory;
  6. import java.text.ParseException;
  7. import java.text.SimpleDateFormat;
  8. import java.time.*;
  9. import java.time.format.DateTimeFormatter;
  10. import java.util.*;
  11. /**
  12. * 时间工具类
  13. *
  14. * @author zhongzheng
  15. */
  16. public class DateUtils extends org.apache.commons.lang3.time.DateUtils
  17. {
  18. public static String YYYY = "yyyy";
  19. public static String YYYY_MM = "yyyy-MM";
  20. public static String YYYY_MM_DD = "yyyy-MM-dd";
  21. public static String YYYYMMDD = "yyyyMMdd";
  22. public static String YYYYMMDDHHMMSS = "yyyyMMddHHmmss";
  23. public static String YYYY_MM_DD_HH_MM_SS = "yyyy-MM-dd HH:mm:ss";
  24. private static String[] parsePatterns = {
  25. "yyyy-MM-dd", "yyyy-MM-dd HH:mm:ss", "yyyy-MM-dd HH:mm", "yyyy-MM",
  26. "yyyy/MM/dd", "yyyy/MM/dd HH:mm:ss", "yyyy/MM/dd HH:mm", "yyyy/MM",
  27. "yyyy.MM.dd", "yyyy.MM.dd HH:mm:ss", "yyyy.MM.dd HH:mm", "yyyy.MM"};
  28. /**
  29. * 获取当前Date型日期
  30. *
  31. * @return Date() 当前日期
  32. */
  33. public static Date getNowDate()
  34. {
  35. return new Date();
  36. }
  37. /**
  38. * 获取当前日期, 默认格式为yyyy-MM-dd
  39. *
  40. * @return String
  41. */
  42. public static String getDate()
  43. {
  44. return dateTimeNow(YYYY_MM_DD);
  45. }
  46. public static final String getTime()
  47. {
  48. return dateTimeNow(YYYY_MM_DD_HH_MM_SS);
  49. }
  50. public static final String dateTimeNow()
  51. {
  52. return dateTimeNow(YYYYMMDDHHMMSS);
  53. }
  54. public static final String dateTimeNow(final String format)
  55. {
  56. return parseDateToStr(format, new Date());
  57. }
  58. public static final String dateTime(final Date date)
  59. {
  60. return parseDateToStr(YYYY_MM_DD, date);
  61. }
  62. public static final String parseDateToStr(final String format, final Date date)
  63. {
  64. return new SimpleDateFormat(format).format(date);
  65. }
  66. public static final Date dateTimeThrow(final String format, final String ts) throws ParseException {
  67. return new SimpleDateFormat(format).parse(ts);
  68. }
  69. public static final Date dateTime(final String format, final String ts)
  70. {
  71. try
  72. {
  73. return new SimpleDateFormat(format).parse(ts);
  74. }
  75. catch (ParseException e)
  76. {
  77. throw new RuntimeException(e);
  78. }
  79. }
  80. public static final Long dateTimeSec(final String format, final String ts)
  81. {
  82. try
  83. {
  84. return (new SimpleDateFormat(format).parse(ts)).getTime()/1000;
  85. }
  86. catch (ParseException e)
  87. {
  88. throw new RuntimeException(e);
  89. }
  90. }
  91. public static String timestampToDateFormat(Long times){
  92. if(Validator.isEmpty(times)){
  93. return "";
  94. }
  95. long t = times.longValue();
  96. t = t * 1000;
  97. Date date = new Date(t);
  98. return DateFormatUtils.format(date, "yyyy/MM/dd");
  99. }
  100. public static Date timeToDate(Long times){
  101. long t = times.longValue();
  102. t = t * 1000;
  103. return new Date(t);
  104. }
  105. public static String timestampToDateFormatMonth(Long times){
  106. if(Validator.isEmpty(times)){
  107. return "";
  108. }
  109. long t = times.longValue();
  110. t = t * 1000;
  111. Date date = new Date(t);
  112. return DateFormatUtils.format(date, "MM月dd号");
  113. }
  114. public static String timestampToDateFormatMonthTwo(Long times){
  115. if(Validator.isEmpty(times)){
  116. return "";
  117. }
  118. long t = times.longValue();
  119. t = t * 1000;
  120. Date date = new Date(t);
  121. return DateFormatUtils.format(date, "MM.dd");
  122. }
  123. public static String timestampToDateFormat(Long times,String patternStr){
  124. if(Validator.isEmpty(times)){
  125. return "";
  126. }
  127. long t = times.longValue();
  128. t = t * 1000;
  129. Date date = new Date(t);
  130. return DateFormatUtils.format(date, patternStr);
  131. }
  132. /**
  133. * 将秒转为时分秒格式【01:01:01】
  134. * @param second 需要转化的秒数
  135. * @return
  136. */
  137. public static String secondConvertHourMinSecond(Long second) {
  138. String str = "";
  139. if (second == null || second < 0) {
  140. return str;
  141. }
  142. // 得到小时
  143. long h = second / 3600;
  144. str = h > 0 ? ((h < 10 ? ("0" + h) : h) + "时") : "";
  145. // 得到分钟
  146. long m = (second % 3600) / 60;
  147. str += m > 0? (m < 10 ? ("0" + m) : m) + "分":"";
  148. //得到剩余秒
  149. long s = second % 60;
  150. str += s > 0?(s < 10 ? ("0" + s) : s)+"秒":"";
  151. return str;
  152. }
  153. public static String timestampToDate(Long times){
  154. if(Validator.isEmpty(times)){
  155. return "";
  156. }
  157. long t = times.longValue();
  158. t = t * 1000;
  159. Date date = new Date(t);
  160. return dateTime(date);
  161. }
  162. /**
  163. * 日期路径 即年/月/日 如2018/08/08
  164. */
  165. public static final String datePath()
  166. {
  167. Date now = new Date();
  168. return DateFormatUtils.format(now, "yyyy/MM/dd");
  169. }
  170. /**
  171. * 日期路径 即年/月/日 如20180808
  172. */
  173. public static final String dateTime()
  174. {
  175. Date now = new Date();
  176. return DateFormatUtils.format(now, "yyyyMMdd");
  177. }
  178. /**
  179. * 日期型字符串转化为日期 格式
  180. */
  181. public static Date parseDate(Object str)
  182. {
  183. if (str == null)
  184. {
  185. return null;
  186. }
  187. try
  188. {
  189. return parseDate(str.toString(), parsePatterns);
  190. }
  191. catch (ParseException e)
  192. {
  193. return null;
  194. }
  195. }
  196. /**
  197. * 获取服务器启动时间
  198. */
  199. public static Date getServerStartDate()
  200. {
  201. long time = ManagementFactory.getRuntimeMXBean().getStartTime();
  202. return new Date(time);
  203. }
  204. /**
  205. * 计算两个时间差
  206. */
  207. public static String getDatePoor(Date endDate, Date nowDate)
  208. {
  209. long nd = 1000 * 24 * 60 * 60;
  210. long nh = 1000 * 60 * 60;
  211. long nm = 1000 * 60;
  212. // long ns = 1000;
  213. // 获得两个时间的毫秒时间差异
  214. long diff = endDate.getTime() - nowDate.getTime();
  215. // 计算差多少天
  216. long day = diff / nd;
  217. // 计算差多少小时
  218. long hour = diff % nd / nh;
  219. // 计算差多少分钟
  220. long min = diff % nd % nh / nm;
  221. // 计算差多少秒//输出结果
  222. // long sec = diff % nd % nh % nm / ns;
  223. return day + "天" + hour + "小时" + min + "分钟";
  224. }
  225. public static Long getNowTime()
  226. {
  227. return System.currentTimeMillis()/1000;
  228. }
  229. /**
  230. * 获取今天凌晨时间戳
  231. */
  232. public static Long getTodayZeroTime()
  233. {
  234. Calendar cal = Calendar.getInstance();
  235. cal.set(cal.get(Calendar.YEAR), cal.get(Calendar.MONTH), cal.get(Calendar.DAY_OF_MONTH), 0, 0, 0);
  236. return cal.getTimeInMillis() / 1000; //今天凌晨
  237. }
  238. public static String formatDate(Date time,String str)
  239. {
  240. SimpleDateFormat sdf = new SimpleDateFormat(str);
  241. return sdf.format(time);
  242. }
  243. /**
  244. * 获取明天凌晨时间戳
  245. */
  246. public static Long getTomorrowZeroTime()
  247. {
  248. Calendar cal = Calendar.getInstance();
  249. cal.set(cal.get(Calendar.YEAR), cal.get(Calendar.MONTH), cal.get(Calendar.DAY_OF_MONTH), 0, 0, 0);
  250. Calendar cal1 = Calendar.getInstance();
  251. cal1.setTime(cal.getTime());
  252. cal1.add(Calendar.DAY_OF_MONTH , +1);
  253. return cal1.getTimeInMillis() / 1000; //明天凌晨
  254. }
  255. /**
  256. * 获取当月第一天的凌晨时间戳
  257. */
  258. public static Long getToMonthZeroTime()
  259. {
  260. Calendar cal = Calendar.getInstance();
  261. cal.set(cal.get(Calendar.YEAR), cal.get(Calendar.MONTH), 1, 0, 0, 0);
  262. return cal.getTime().getTime()/1000;
  263. }
  264. /**
  265. * 根据当前日期获得所在周的日期区间(周一和周日日期)
  266. */
  267. public static Map<String, Long> getTimeInterval(Date date){
  268. Map<String, Long> map = new HashMap<>();
  269. Calendar cal = Calendar.getInstance();
  270. cal.setTime(date);
  271. // 判断要计算的日期是否是周日,如果是则减一天计算周六的,否则会出问题,计算到下一周去了
  272. int dayWeek = cal.get(Calendar.DAY_OF_WEEK);// 获得当前日期是一个星期的第几天
  273. if(1 == dayWeek){
  274. cal.add(Calendar.DAY_OF_MONTH,-1);
  275. }
  276. // 设置一个星期的第一天,按中国的习惯一个星期的第一天是星期一
  277. cal.setFirstDayOfWeek(Calendar.MONDAY);
  278. // 获得当前日期是一个星期的第几天
  279. int day = cal.get(Calendar.DAY_OF_WEEK);
  280. // 根据日历的规则,给当前日期减去星期几与一个星期第一天的差值
  281. cal.add(Calendar.DATE, cal.getFirstDayOfWeek() - day);
  282. Long imptimeBegin = cal.getTime().getTime();
  283. cal.add(Calendar.DATE,6);
  284. Long imptimeEnd = cal.getTime().getTime();
  285. map.put("start", imptimeBegin/1000);
  286. map.put("end", imptimeEnd/1000);
  287. return map;
  288. }
  289. /**
  290. * 根据当前日期获得上周的日期区间(上周周一和周日日期)
  291. */
  292. public static Map<String, Long> getLastTimeInterval(Date date){
  293. Map<String, Long> map = new HashMap<>();
  294. Calendar calendar1 = Calendar.getInstance();
  295. Calendar calendar2 = Calendar.getInstance();
  296. calendar1.setTime(date);
  297. calendar2.setTime(date);
  298. int dayOfWeek = calendar1.get(Calendar.DAY_OF_WEEK) - 1;
  299. if(dayOfWeek <= 0){
  300. dayOfWeek = 7;
  301. }
  302. int offset1 = 1 - dayOfWeek;
  303. int offset2 = 7 - dayOfWeek;
  304. calendar1.add(Calendar.DATE, offset1 - 7);
  305. calendar2.add(Calendar.DATE, offset2 - 7);
  306. // last Monday
  307. Long lastBeginDate = calendar1.getTime().getTime();
  308. // last Sunday
  309. Long lastEndDate = calendar2.getTime().getTime();
  310. map.put("laststart", lastBeginDate/1000);
  311. map.put("lastend", lastEndDate/1000);
  312. return map;
  313. }
  314. /**
  315. * 获取日期格式订单号
  316. * @return
  317. */
  318. public static String getDateOrderSn()
  319. {
  320. DateTimeFormatter ofPattern = DateTimeFormatter.ofPattern("yyyyMMddHHmmss");
  321. String localDate = (LocalDateTime.now().format(ofPattern)).substring(2);
  322. //随机数
  323. String randomNumeric = RandomStringUtils.randomNumeric(8);
  324. return localDate+randomNumeric;
  325. }
  326. public static String getDateInputOrderSn()
  327. {
  328. return "LD"+getDateOrderSn();
  329. }
  330. public static String getPayOrderSn()
  331. {
  332. return "P"+getDateOrderSn();
  333. }
  334. public static String getInvoiceOrderSn()
  335. {
  336. DateTimeFormatter ofPattern = DateTimeFormatter.ofPattern("yyyyMMddHHmmss");
  337. String localDate = (LocalDateTime.now().format(ofPattern)).substring(2);
  338. //随机数
  339. String randomNumeric = RandomStringUtils.randomNumeric(4);
  340. return "IN"+localDate+randomNumeric;
  341. }
  342. public static String getTagOrderSn(String tag)
  343. {
  344. return tag+getDateOrderSn();
  345. }
  346. public static String secToTime(int time) {
  347. String timeStr = null;
  348. int hour = 0;
  349. int minute = 0;
  350. int second = 0;
  351. if (time <= 0)
  352. return "00:00";
  353. else {
  354. minute = time / 60;
  355. if (minute < 60) {
  356. second = time % 60;
  357. timeStr = "00:"+unitFormat(minute) + ":" + unitFormat(second);
  358. } else {
  359. hour = minute / 60;
  360. if (hour > 99){
  361. return "99:59:59";
  362. }
  363. minute = minute % 60;
  364. second = time - hour * 3600 - minute * 60;
  365. timeStr = unitFormat(hour) + ":" + unitFormat(minute) + ":" + unitFormat(second);
  366. }
  367. }
  368. return timeStr;
  369. }
  370. public static String unitFormat(int i) {
  371. String retStr = null;
  372. if (i >= 0 && i < 10)
  373. retStr = "0" + Integer.toString(i);
  374. else
  375. retStr = "" + i;
  376. return retStr;
  377. }
  378. public static Integer durationFormat(String duration) {
  379. int index1=duration.indexOf(":");
  380. int index2=duration.indexOf(":",index1+1);
  381. int hh=Integer.parseInt(duration.substring(0,index1));
  382. int mi=Integer.parseInt(duration.substring(index1+1,index2));
  383. int ss=Integer.parseInt(duration.substring(index2+1));
  384. return hh*60*60+mi*60+ss;
  385. }
  386. public static Integer dayBetween(Long s1,Long s2) {
  387. String date1str = timestampToDateFormat(s1);
  388. String date2str = timestampToDateFormat(s2);
  389. int count = 0;
  390. if("".equals(date1str) || date1str == null || "".equals(date2str) || date2str == null) {
  391. return count;
  392. }
  393. SimpleDateFormat format = new SimpleDateFormat("yyyy/MM/dd");
  394. try {
  395. Date date1 = format.parse(date1str);
  396. Date date2 = format.parse(date2str);
  397. count = ((int) ((date1.getTime() - date2.getTime()) / (1000*3600*24)));
  398. return count;
  399. }catch (Exception e){
  400. return null;
  401. }
  402. }
  403. public static Integer getTodayWeek(){
  404. Calendar calendar = Calendar.getInstance();
  405. calendar.setTime(new Date());
  406. int weekIdx = calendar.get(Calendar.DAY_OF_WEEK) - 1;
  407. switch (weekIdx) {
  408. case 1:
  409. return 1;
  410. case 2:
  411. return 2;
  412. case 3:
  413. return 3;
  414. case 4:
  415. return 4;
  416. case 5:
  417. return 5;
  418. case 6:
  419. return 6;
  420. default:
  421. return 7;
  422. }
  423. }
  424. public static LocalDate[] getDateArray() {
  425. // 创建一个长度为30的数组
  426. LocalDate[] dates = new LocalDate[30];
  427. // 获取今天的日期
  428. LocalDate today = LocalDate.now();
  429. // 用循环给数组赋值
  430. for (int i = 0; i < dates.length; i++) {
  431. // 用today.plusDays(i)得到第i天的日期
  432. dates[i] = today.plusDays(i);
  433. }
  434. // 返回数组
  435. return dates;
  436. }
  437. static List<String> holiday =new ArrayList<>();
  438. static List<String> extraWorkDay =new ArrayList<>();
  439. public static Boolean isWorkingDay(long time) {
  440. LocalDateTime dateTime = LocalDateTime.ofInstant(Instant.ofEpochMilli(time), ZoneOffset.of("+8"));
  441. String formatTime = dateTime.format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
  442. initHoliday();
  443. initExtraWorkDay();
  444. //是否加班日
  445. if(extraWorkDay.contains(formatTime)){
  446. return true;
  447. }
  448. //是否节假日
  449. if(holiday.contains(formatTime)){
  450. return false;
  451. }
  452. //如果是1-5表示周一到周五 是工作日
  453. DayOfWeek week = dateTime.getDayOfWeek();
  454. if(week==DayOfWeek.SATURDAY||week==DayOfWeek.SUNDAY){
  455. return false;
  456. }
  457. return true;
  458. }
  459. /**
  460. * 初始化节假日
  461. */
  462. public static void initHoliday(){
  463. holiday.add("2023-06-22");
  464. holiday.add("2023-06-23");
  465. holiday.add("2023-09-29");
  466. holiday.add("2023-09-30");
  467. holiday.add("2023-10-01");
  468. holiday.add("2023-10-02");
  469. holiday.add("2023-10-03");
  470. holiday.add("2023-10-04");
  471. holiday.add("2023-10-05");
  472. holiday.add("2023-10-06");
  473. }
  474. /**
  475. * 初始化额外加班日
  476. */
  477. public static void initExtraWorkDay(){
  478. extraWorkDay.add("2023-06-25");
  479. extraWorkDay.add("2023-10-07");
  480. extraWorkDay.add("2023-10-08");
  481. }
  482. /**
  483. * 指定时间往前或往后推n天
  484. *
  485. * @param dateTime 指定时间
  486. * @param x 指定天数
  487. * @return
  488. */
  489. public static Long getDayBefore(Long dateTime, int x) {
  490. Calendar c = Calendar.getInstance();
  491. Date date = new Date(dateTime*1000);
  492. c.setTime(date);
  493. int day = c.get(Calendar.DATE);
  494. c.set(Calendar.DATE, day - x); //往前推几天
  495. //c.set(Calendar.DATE, day + x); 往后推几天
  496. return c.getTime().getTime()/1000;
  497. }
  498. }