DateUtil.java 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549
  1. package com.happy.Until;
  2. import java.io.File;
  3. import java.text.DateFormat;
  4. import java.text.ParseException;
  5. import java.text.SimpleDateFormat;
  6. import java.util.ArrayList;
  7. import java.util.Calendar;
  8. import java.util.Date;
  9. import java.util.List;
  10. import java.util.regex.Pattern;
  11. /**
  12. * @author xieli
  13. * @date 2023/8/1 17:34
  14. * @description 时间工具类 date
  15. */
  16. public class DateUtil
  17. {
  18. public DateUtil() {
  19. }
  20. public static String Time_Formatter_Day = "yyyy-MM-dd";
  21. public static String Time_Formatter_yyyyMMdd = "yyyyMMdd";
  22. public static String Time_Formatter_Second = "yyyy-MM-dd HH:mm:ss";
  23. // 获取昨天时间
  24. public static String getYesturday(Date date, String format) {
  25. Calendar nowTime2 = Calendar.getInstance();
  26. nowTime2.setTime(date);
  27. nowTime2.add(Calendar.DATE, -1);
  28. SimpleDateFormat simpleDateFormat = new SimpleDateFormat(format);
  29. return simpleDateFormat.format(nowTime2.getTime());
  30. }
  31. public static String getCurrentYear() {
  32. SimpleDateFormat sdf = new SimpleDateFormat("yyyy");
  33. Date date = new Date();
  34. return sdf.format(date);
  35. }
  36. /**
  37. * 判断 firstDate 是否在 secondDate 之前或相等.
  38. * @param firstDate .
  39. * @param secondDate .
  40. * @return firstDate 在 secondDate 之前或相等时返回 true,否则返回 false.
  41. */
  42. public static boolean isBeforeOrEqual(Date firstDate, Date secondDate) {
  43. if (secondDate == null) {
  44. return true;
  45. }
  46. if (firstDate.compareTo(secondDate) <= 0) {
  47. return true;
  48. }
  49. return false;
  50. }
  51. /**
  52. * 数据库使用mysql的datetime类型时读取出来数据后出现“.0”
  53. * 此工具类进行类型转化
  54. * @param time
  55. * @return
  56. */
  57. public static String convertDateTimeMysql(String time)
  58. {
  59. if (Func.checkNull(time))
  60. return time;
  61. try {
  62. SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
  63. Date date = format.parse(time);
  64. String resultTime= format.format(date);
  65. return resultTime;
  66. } catch (ParseException e) {
  67. // throw new RuntimeException(e);
  68. return time.replace(".0","");
  69. }
  70. }
  71. /**
  72. * 比较日期
  73. * @param firstDate 第一个
  74. * @param secondDate 第二个
  75. * @return boolean
  76. */
  77. public static boolean isAfterOrEqual(Date firstDate, Date secondDate) {
  78. if (secondDate == null) {
  79. return true;
  80. }
  81. if (firstDate.compareTo(secondDate) >= 0) {
  82. return true;
  83. }
  84. return false;
  85. }
  86. /**
  87. * 验证日期格式是否正确.
  88. * @param datestr .
  89. * @return .
  90. */
  91. public static boolean isISO8601Date(String datestr) {
  92. return Pattern
  93. .compile(
  94. "^((((1[6-9]|[2-9]\\d)\\d{2})-(0?[13578]|1[02])-(0?[1-9]|[12]\\d|3[01]))|(((1[6-9]|[2-9]\\d)\\d{2})-(0?[13456789]|1[012])-(0?[1-9]|[12]\\d|30))|(((1[6-9]|[2-9]\\d)\\d{2})-0?2-(0?[1-9]|1\\d|2[0-8]))|(((1[6-9]|[2-9]\\d)(0[48]|[2468][048]|[13579][26])|((16|[2468][048]|[3579][26])00))-0?2-29-))$")
  95. .matcher(datestr).matches();
  96. }
  97. /**
  98. * 获取两个指定日期相差的天数.
  99. * @param firstDate .
  100. * @param secondDate .
  101. * @return .
  102. */
  103. public static int getBetweenDay(Date firstDate, Date secondDate) {
  104. // 时间格式相同,获取两时间差的秒数
  105. long betweendDateBySeconds = firstDate.getTime() - secondDate.getTime();
  106. // 得到天数(保持正负号)
  107. return (int) (betweendDateBySeconds / (1000 * 3600 * 24));
  108. }
  109. /**
  110. * 获取系统当前时间.
  111. * @return .
  112. */
  113. public static Date getCurrentDate() {
  114. return new Date();
  115. }
  116. /**
  117. * 年份
  118. * @param datIn 日期
  119. * @return int
  120. */
  121. public static int getYear(Date datIn) {
  122. Calendar calendar = Calendar.getInstance();
  123. calendar.setTime(datIn);
  124. return calendar.get(Calendar.YEAR);
  125. }
  126. /**
  127. * 月份
  128. * @param datIn 日期
  129. * @return int
  130. */
  131. public static int getMonth(Date datIn) {
  132. Calendar calendar = Calendar.getInstance();
  133. calendar.setTime(datIn);
  134. return calendar.get(Calendar.MONTH) + 1;
  135. }
  136. /**
  137. * 日
  138. * @param datIn 日期
  139. * @return int
  140. */
  141. public static int getDay(Date datIn) {
  142. Calendar calendar = Calendar.getInstance();
  143. calendar.setTime(datIn);
  144. return calendar.get(Calendar.DAY_OF_MONTH);
  145. }
  146. /**
  147. * 小时
  148. * @param datIn 日期
  149. * @return int
  150. */
  151. public static int getHour(Date datIn) {
  152. Calendar calendar = Calendar.getInstance();
  153. calendar.setTime(datIn);
  154. return calendar.get(Calendar.HOUR_OF_DAY);
  155. }
  156. /**
  157. * 分钟
  158. * @param datIn 日期
  159. * @return int
  160. */
  161. public static int getMinute(Date datIn) {
  162. Calendar calendar = Calendar.getInstance();
  163. calendar.setTime(datIn);
  164. return calendar.get(Calendar.MINUTE);
  165. }
  166. /**
  167. * 秒数
  168. * @param datIn 日期
  169. * @return int
  170. */
  171. public static int getSecond(Date datIn) {
  172. Calendar calendar = Calendar.getInstance();
  173. calendar.setTime(datIn);
  174. return calendar.get(Calendar.SECOND);
  175. }
  176. /**
  177. * 格式化日期
  178. * @param patern 格式字符
  179. * @return String
  180. */
  181. public static String getFormatDate(String patern) {
  182. return new SimpleDateFormat(patern).format(new Date());
  183. }
  184. /**
  185. * 格式化日期
  186. * @param datIn 日期
  187. * @return String
  188. */
  189. public static String getFormatPaternDate(Date datIn) {
  190. return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(datIn);
  191. }
  192. /**
  193. * 将指定字符串,通过指定格式转换为日期对象.
  194. * @param dateStr 字符串
  195. * @return Date
  196. */
  197. public static Date parseDate(String dateStr, String formatter) {
  198. try {
  199. if (Func.checkNullOrEmpty(dateStr)) {
  200. return null;
  201. }
  202. return new SimpleDateFormat(formatter).parse(dateStr);
  203. } catch (ParseException e) {
  204. return null;
  205. }
  206. }
  207. /**
  208. * 将指定字符串,通过指定格式转换为日期对象.
  209. * @param dateStr 字符串
  210. * @return Date
  211. */
  212. public static Date parseDateOnly(String dateStr) {
  213. if (Func.checkNullOrEmpty(dateStr)) {
  214. return null;
  215. }
  216. try {
  217. return new SimpleDateFormat("yyyy-MM-dd").parse(dateStr);
  218. } catch (ParseException e) {
  219. try {
  220. return new SimpleDateFormat("yyyy/MM/dd").parse(dateStr);
  221. } catch (Exception e2) {
  222. new Exception("时间格式错误:" + e2.getMessage()).printStackTrace();
  223. }
  224. }
  225. return null;
  226. }
  227. /**
  228. * 转化成时间区间.
  229. * @param startTime 字符串开始时间
  230. * @param endTime 字符串
  231. * @return Date
  232. */
  233. public static String convertTimeArea(String startTime, String endTime) {
  234. if (Func.checkNullOrEmpty(startTime) || Func.checkNullOrEmpty(endTime)) {
  235. return null;
  236. }
  237. try {
  238. Date start = new SimpleDateFormat(Time_Formatter_Day).parse(startTime);
  239. Date end = new SimpleDateFormat(Time_Formatter_Day).parse(endTime);
  240. String startDate = parseDateToStr(start,"mmdd");
  241. String endDate = parseDateToStr(end,"mmdd");
  242. return startDate + "-" +endDate;
  243. } catch (ParseException e) {
  244. new Exception("时间格式错误:" + e.getMessage()).printStackTrace();
  245. }
  246. return null;
  247. }
  248. /**
  249. * 将日期date转化成string
  250. * @param date
  251. * @return
  252. */
  253. public static String parseDateToStr(Date date, String formatter) {
  254. SimpleDateFormat sdf = new SimpleDateFormat(formatter);
  255. return sdf.format(date);
  256. }
  257. /**
  258. * 增加日期
  259. * @param date 日期
  260. * @param dateField 字段
  261. * @param dateAmount 数量
  262. * @return Date
  263. */
  264. public static Date addDate(Date date, int dateField, int dateAmount) {
  265. Calendar calendar = Calendar.getInstance();
  266. calendar.setTime(date);
  267. calendar.add(dateField, dateAmount);
  268. return calendar.getTime();
  269. }
  270. /**
  271. * 格式化指定日期格式
  272. * @param datIn 日期内容
  273. * @param formatStr 格式化字符
  274. * @return 格式化之后的日期对象
  275. * @throws ParseException 转换异常
  276. */
  277. public static Date formateDate(Date datIn, String formatStr) throws ParseException {
  278. String dateStr = new SimpleDateFormat(formatStr).format(datIn);
  279. return new SimpleDateFormat(formatStr).parse(dateStr);
  280. }
  281. /**
  282. * 获取两个日期相差的月数
  283. * @param c1 较大的日期
  284. * @param c2 较小的日期
  285. * @return 如果d1>d2返回 月数差 否则返回0
  286. */
  287. public static int getMonthDiff(Calendar c1, Calendar c2) {
  288. if (c1.getTimeInMillis() < c2.getTimeInMillis()) {
  289. return 0;
  290. }
  291. int year1 = c1.get(Calendar.YEAR);
  292. int year2 = c2.get(Calendar.YEAR);
  293. int month1 = c1.get(Calendar.MONTH);
  294. int month2 = c2.get(Calendar.MONTH);
  295. int day1 = c1.get(Calendar.DAY_OF_MONTH);
  296. int day2 = c2.get(Calendar.DAY_OF_MONTH);
  297. // 获取年的差值 假设 d1 = 2015-8-16 d2 = 2011-9-30
  298. int yearInterval = year1 - year2;
  299. // 如果 d1的 月-日 小于 d2的 月-日 那么 yearInterval-- 这样就得到了相差的年数
  300. if (month1 < month2 || month1 == month2 && day1 < day2) {
  301. yearInterval--;
  302. }
  303. // 获取月数差值
  304. int monthInterval = (month1 + 12) - month2;
  305. if (day1 < day2) {
  306. monthInterval--;
  307. }
  308. monthInterval %= 12;
  309. return yearInterval * 12 + monthInterval;
  310. }
  311. /**
  312. * 获得两个日期之间的所有月份
  313. * @param minDate minDate
  314. * @param maxDate maxDate
  315. * @return List<String>
  316. * @throws ParseException ParseException
  317. */
  318. public static List<String> getMonthBetween(String minDate, String maxDate) throws ParseException {
  319. ArrayList<String> result = new ArrayList<String>();
  320. SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");//格式化为年月
  321. Calendar min = Calendar.getInstance();
  322. Calendar max = Calendar.getInstance();
  323. min.setTime(sdf.parse(minDate));
  324. min.set(min.get(Calendar.YEAR), min.get(Calendar.MONTH), 1);
  325. max.setTime(sdf.parse(maxDate));
  326. max.set(max.get(Calendar.YEAR), max.get(Calendar.MONTH), 2);
  327. Calendar curr = min;
  328. while (curr.before(max)) {
  329. result.add(sdf.format(curr.getTime()));
  330. curr.add(Calendar.MONTH, 1);
  331. }
  332. return result;
  333. }
  334. /**
  335. * 转换日期 yyyy/MM/dd
  336. * @param str 对象
  337. * @return boolean
  338. */
  339. @SuppressWarnings("deprecation")
  340. public static boolean isDateStr(String str, boolean hasDay) {
  341. boolean convertSuccess = true;
  342. // 指定日期格式为四位年/两位月份/两位日期,注意yyyy-MM-dd区分大小写;
  343. SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
  344. if (!hasDay) {
  345. format = new SimpleDateFormat("yyyy-MM");
  346. }
  347. try {
  348. // 设置lenient为false.
  349. // 否则SimpleDateFormat会比较宽松地验证日期,比如2007/02/29会被接受,并转换成2007/03/01
  350. format.setLenient(false);
  351. format.parse(str);
  352. } catch (ParseException e) {
  353. try {
  354. SimpleDateFormat formatt = new SimpleDateFormat("yyyy/MM/dd");
  355. if (!hasDay) {
  356. formatt = new SimpleDateFormat("yyyy/MM");
  357. }
  358. formatt.setLenient(false);
  359. Date tempDate = formatt.parse(str);
  360. // 年份大于9999年 则视为非法;
  361. if (tempDate.getYear() > 8099) {
  362. convertSuccess = false;
  363. }
  364. } catch (Exception e2) {
  365. convertSuccess = false;
  366. }
  367. }
  368. return convertSuccess;
  369. }
  370. /**
  371. * 根据当前时间获取文件夹
  372. * @return String
  373. */
  374. public static String getCurrentDateFolder() {
  375. Calendar now = Calendar.getInstance();
  376. int year = now.get(Calendar.YEAR);
  377. int month = now.get(Calendar.MONTH) + 1;
  378. int day = now.get(Calendar.DAY_OF_MONTH);
  379. return year + File.separator + month + File.separator + day + File.separator;
  380. }
  381. /**
  382. * 对比时间(精确到天)
  383. * @param date1
  384. * @param date2
  385. */
  386. public static boolean compareDateTimeSpecial(String date1, String date2, String order) {
  387. Date d1 = parseDateOnly(date1);
  388. Date d2 = parseDateOnly(date2);
  389. if (d1.equals(d2)) {
  390. return false;
  391. } else if (d1.before(d2)) {
  392. return true;
  393. } else {
  394. return false;
  395. }
  396. }
  397. /**
  398. * 获取两个日期之间相差多少天
  399. * @param date1
  400. * @param date2
  401. * @return
  402. */
  403. public static int getDayDiff(String date1,String date2)
  404. {
  405. DateFormat dft = new SimpleDateFormat("yyyy-MM-dd");
  406. Date star = parseDateOnly(date1);
  407. Date endDay=parseDateOnly(date2);
  408. Date nextDay=star;
  409. int i=0;
  410. while(nextDay.before(endDay)){//当明天不在结束时间之前是终止循环
  411. Calendar cld = Calendar.getInstance();
  412. cld.setTime(star);
  413. cld.add(Calendar.DATE, 1);
  414. star = cld.getTime();
  415. //获得下一天日期字符串
  416. nextDay = star;
  417. i++;
  418. }
  419. return i;
  420. }
  421. /**
  422. * 获得两个日期之间的所有日期
  423. *
  424. * @param startDate 开始日期
  425. * @param endDate 结束日期
  426. */
  427. public static List<Date> getDateListBetween(Date startDate, Date endDate) {
  428. List<Date> result = new ArrayList<>();
  429. // result.add(parseDateToStr(startDate, Time_Formatter_Day));
  430. result.add(startDate);
  431. Calendar calBegin = Calendar.getInstance();
  432. // 使用给定的 Date 设置此 Calendar 的时间
  433. calBegin.setTime(startDate);
  434. Calendar calEnd = Calendar.getInstance();
  435. // 使用给定的 Date 设置此 Calendar 的时间
  436. calEnd.setTime(endDate);
  437. // 测试此日期是否在指定日期之后
  438. while (endDate.after(calBegin.getTime())) {
  439. // 根据日历的规则,为给定的日历字段添加或减去指定的时间量
  440. calBegin.add(Calendar.DAY_OF_MONTH, 1);
  441. // result.add(parseDateToStr(calBegin.getTime(), Time_Formatter_Day));
  442. result.add(calBegin.getTime());
  443. }
  444. return result;
  445. }
  446. /**
  447. * 获得两个日期之间的所有日期
  448. *
  449. * @param startDate 开始日期
  450. * @param endDate 结束日期
  451. */
  452. public static List<String> getDateStrListBetween(Date startDate, Date endDate) {
  453. List<String> result = new ArrayList<>();
  454. result.add(parseDateToStr(startDate, Time_Formatter_Day));
  455. Calendar calBegin = Calendar.getInstance();
  456. // 使用给定的 Date 设置此 Calendar 的时间
  457. calBegin.setTime(startDate);
  458. Calendar calEnd = Calendar.getInstance();
  459. // 使用给定的 Date 设置此 Calendar 的时间
  460. calEnd.setTime(endDate);
  461. // 测试此日期是否在指定日期之后
  462. while (endDate.after(calBegin.getTime())) {
  463. // 根据日历的规则,为给定的日历字段添加或减去指定的时间量
  464. calBegin.add(Calendar.DAY_OF_MONTH, 1);
  465. result.add(parseDateToStr(calBegin.getTime(), Time_Formatter_Day));
  466. }
  467. return result;
  468. }
  469. /**
  470. * 判断当前时间是否在[startTime, endTime]区间
  471. *
  472. * @param dataIn 传入的时间
  473. * @param startTime 开始时间
  474. * @param endTime 结束时间
  475. */
  476. public static boolean isEffectiveDate(Date dataIn, Date startTime, Date endTime) {
  477. if (dataIn.getTime() == startTime.getTime()
  478. || dataIn.getTime() == endTime.getTime()) {
  479. return true;
  480. }
  481. Calendar date = Calendar.getInstance();
  482. date.setTime(dataIn);
  483. Calendar begin = Calendar.getInstance();
  484. begin.setTime(startTime);
  485. Calendar end = Calendar.getInstance();
  486. end.setTime(endTime);
  487. return date.after(begin) && date.before(end);
  488. }
  489. }