DateTimeUtils.java 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541
  1. package com.ydtech.utils;
  2. import org.joda.time.DateTime;
  3. import org.joda.time.Days;
  4. import org.joda.time.format.DateTimeFormat;
  5. import org.joda.time.format.DateTimeFormatter;
  6. import java.util.Date;
  7. /**
  8. * 日期时间工具类
  9. */
  10. public final class DateTimeUtils {
  11. /**
  12. * 年(yyyy)
  13. */
  14. public static final String YEAR = "yyyy";
  15. /**
  16. * 年-月(yyyy-MM)
  17. */
  18. public static final String YEAR_MONTH = "yyyy-MM";
  19. /**
  20. * 年-月-日(yyyy-MM-dd)
  21. */
  22. public static final String YEAR_MONTH_DAY = "yyyy-MM-dd";
  23. /**
  24. * 年月日(yyyyMMdd)
  25. */
  26. public static final String YEAR_MONTH_DAY_SIMPLE = "yyyyMMdd";
  27. /**
  28. * 年-月-日 小时(yyyy-MM-dd HH)
  29. */
  30. public static final String YEAR_MONTH_DAY_HOUR = "yyyy-MM-dd HH";
  31. /**
  32. * 年-月-日 小时(yyyy-MM-dd HH)中文输出
  33. */
  34. public static final String YEAR_MONTH_DAY_HOUR_CN = "yyyy年MM月dd日HH时";
  35. /**
  36. * 年-月-日 小时:分钟(yyyy-MM-dd HH:mm)
  37. */
  38. public static final String YEAR_MONTH_DAY_HOUR_MINUTE = "yyyy-MM-dd HH:mm";
  39. /**
  40. * 年-月-日 小时:分钟:秒钟(yyyy-MM-dd HH:mm:ss)
  41. */
  42. public static final String YEAR_MONTH_DAY_HOUR_MINUTE_SECOND = "yyyy-MM-dd HH:mm:ss";
  43. /**
  44. * 年月日小时分钟秒钟(yyyyMMddHHmmss)
  45. */
  46. public static final String YEAR_MONTH_DAY_HOUR_MINUTE_SECOND_SIMPLE = "yyyyMMddHHmmss";
  47. /**
  48. * 小时:分钟:秒钟(HH:mm:ss)
  49. */
  50. public static final String HOUR_MINUTE_SECOND = "HH:mm:ss";
  51. /**
  52. * 小时:分钟(HH:mm)
  53. */
  54. public static final String HOUR_MINUTE = "HH:mm";
  55. /**
  56. * 月.日(M.d)
  57. */
  58. public static final String MONTH_DAY = "M.d";
  59. /**
  60. * 一天的秒数
  61. */
  62. private static final int DAY_SECOND = 24 * 60 * 60;
  63. /**
  64. * 一小时的秒数
  65. */
  66. private static final int HOUR_SECOND = 60 * 60;
  67. /**
  68. * 一分钟的秒数
  69. */
  70. private static final int MINUTE_SECOND = 60;
  71. /**
  72. * 格式化日期时间
  73. *
  74. * @param date Date对象
  75. * @param pattern 模式
  76. * @return 格式化后的日期时间字符串
  77. */
  78. public static String format(Date date, String pattern) {
  79. if (date == null)
  80. return "";
  81. return new DateTime(date).toString(pattern);
  82. }
  83. /**
  84. * 格式化日期时间字符串
  85. *
  86. * @param dateString 日期时间字符串
  87. * @param pattern 模式
  88. * @return Date对象
  89. */
  90. public static Date formatDateString(String dateString, String pattern) {
  91. try {
  92. DateTimeFormatter dateTimeFormatter = DateTimeFormat.forPattern(pattern);
  93. return dateTimeFormatter.parseDateTime(dateString).toDate();
  94. } catch (Exception e) {
  95. return null;
  96. }
  97. }
  98. /**
  99. * 根据秒数获得x天x小时x分钟x秒字符串
  100. *
  101. * @param second 秒数
  102. * @return x天x小时x分钟x秒字符串
  103. */
  104. public static String getDayHourMinuteSecond(int second) {
  105. if (second == 0) {
  106. return "0秒";
  107. }
  108. StringBuilder sb = new StringBuilder();
  109. int days = second / DAY_SECOND;
  110. if (days > 0) {
  111. sb.append(days);
  112. sb.append("天");
  113. second -= days * DAY_SECOND;
  114. }
  115. int hours = second / HOUR_SECOND;
  116. if (hours > 0) {
  117. sb.append(hours);
  118. sb.append("小时");
  119. second -= hours * HOUR_SECOND;
  120. }
  121. int minutes = second / MINUTE_SECOND;
  122. if (minutes > 0) {
  123. sb.append(minutes);
  124. sb.append("分钟");
  125. second -= minutes * MINUTE_SECOND;
  126. }
  127. if (second > 0) {
  128. sb.append(second);
  129. sb.append("秒");
  130. }
  131. return sb.toString();
  132. }
  133. /**
  134. * 根据秒数获得x天x小时x分钟字符串
  135. *
  136. * @param second 秒数
  137. * @return x天x小时x分钟字符串
  138. */
  139. public static String getDayHourMinute(int second) {
  140. if (second == 0) {
  141. return "0分钟";
  142. }
  143. StringBuilder sb = new StringBuilder();
  144. int days = second / DAY_SECOND;
  145. if (days > 0) {
  146. sb.append(days);
  147. sb.append("天");
  148. second -= days * DAY_SECOND;
  149. }
  150. int hours = second / HOUR_SECOND;
  151. if (hours > 0) {
  152. sb.append(hours);
  153. sb.append("小时");
  154. second -= hours * HOUR_SECOND;
  155. }
  156. int minutes = second / MINUTE_SECOND;
  157. if (minutes > 0) {
  158. sb.append(minutes);
  159. sb.append("分钟");
  160. }
  161. return sb.toString();
  162. }
  163. /**
  164. * 获取只含有年月日的DateTime对象
  165. *
  166. * @param dateTime DateTime对象
  167. * @return 只含有年月日的DateTime对象
  168. */
  169. public static DateTime getDateOnly(DateTime dateTime) {
  170. return new DateTime(dateTime.toString(YEAR_MONTH_DAY));
  171. }
  172. /**
  173. * 获取当前周的周一和下周一
  174. *
  175. * @return 日期数组(索引0为周一,索引1为下周一)
  176. */
  177. public static Date[] getMondayAndNextMonday() {
  178. DateTime dateTime = getDateOnly(new DateTime());
  179. DateTime monday = dateTime.dayOfWeek().withMinimumValue();
  180. DateTime nextMonday = monday.plusDays(7);
  181. return new Date[]{monday.toDate(), nextMonday.toDate()};
  182. }
  183. /**
  184. * 获取指定时间的周一和周日
  185. *
  186. * @param dateTime DateTime对象
  187. * @return 日期数组(索引0为周一,索引1为周日)
  188. */
  189. public static Date[] getMondayAndSunday(DateTime dateTime) {
  190. dateTime = getDateOnly(dateTime);
  191. DateTime monday = dateTime.dayOfWeek().withMinimumValue();
  192. DateTime sunday = monday.plusDays(6);
  193. return new Date[]{monday.toDate(), sunday.toDate()};
  194. }
  195. /**
  196. * 和当前时间相比的天数差(正数为大于天数,负数为小于天数,零为同一天)
  197. *
  198. * @param date Date对象
  199. * @return 和当前时间相比的天数差
  200. */
  201. public static int compareDaysWithNow(Date date) {
  202. return Days.daysBetween(new DateTime(), new DateTime(date)).getDays();
  203. }
  204. /**
  205. * 和今天相比的天数差(正数为大于天数,负数为小于天数,零为同一天)
  206. *
  207. * @param date Date对象
  208. * @return 和今天相比的天数差
  209. */
  210. public static int compareDaysWithToday(Date date) {
  211. DateTime today = new DateTime();
  212. today = new DateTime(today.getYear(), today.getMonthOfYear(), today.getDayOfMonth(), 0, 0, 0, 0);
  213. DateTime compareDay = new DateTime(date);
  214. compareDay = new DateTime(compareDay.getYear(), compareDay.getMonthOfYear(), compareDay.getDayOfMonth(), 0, 0, 0, 0);
  215. return Days.daysBetween(today, compareDay).getDays();
  216. }
  217. /**
  218. * 比较时间a到时间b的天数差
  219. *
  220. * @param a 时间a
  221. * @param b 时间b
  222. * @return 相差天数
  223. */
  224. public static int compareDaysWithDay(Date a, Date b) {
  225. DateTime today = new DateTime(b);
  226. today = new DateTime(today.getYear(), today.getMonthOfYear(), today.getDayOfMonth(), 0, 0, 0, 0);
  227. DateTime compareDay = new DateTime(a);
  228. compareDay = new DateTime(compareDay.getYear(), compareDay.getMonthOfYear(), compareDay.getDayOfMonth(), 0, 0, 0, 0);
  229. return Days.daysBetween(today, compareDay).getDays();
  230. }
  231. /**
  232. * 比较两个时间是否相等(省略毫秒)
  233. *
  234. * @param date Date对象
  235. * @param compareDate 比较Date对象
  236. * @return 是否相等
  237. */
  238. public static boolean compareDateIgnoreMillisecond(Date date, Date compareDate) {
  239. if (date == null && compareDate == null) {
  240. return true;
  241. } else if (date == null && compareDate != null) {
  242. return false;
  243. } else if (date != null && compareDate == null) {
  244. return false;
  245. }
  246. return (date.getTime() / 1000 == compareDate.getTime() / 1000);
  247. }
  248. /**
  249. * 根据秒数获取天数
  250. *
  251. * @param second 秒数
  252. * @return 天数
  253. */
  254. public static int getDay(int second) {
  255. return second / DAY_SECOND;
  256. }
  257. /**
  258. * 获取和今天相比的日期字符串
  259. *
  260. * @param date Date对象
  261. * @return 和今天相比的日期字符串
  262. */
  263. public static String getCompareWithTodayDateString(Date date) {
  264. int days = Math.abs(DateTimeUtils.compareDaysWithToday(date));
  265. String dateString = "";
  266. if (days == 0) {
  267. dateString = "今天";
  268. } else if (days == 1) {
  269. dateString = "昨天";
  270. } else if (days == 2) {
  271. dateString = "2天前";
  272. } else if (days == 3) {
  273. dateString = "3天前";
  274. } else if (days == 4) {
  275. dateString = "4天前";
  276. } else if (days == 5) {
  277. dateString = "5天前";
  278. } else if (days == 6) {
  279. dateString = "6天前";
  280. } else if (days > 6 && days <= 14) {
  281. dateString = "1周前";
  282. } else if (days > 14 && days <= 21) {
  283. dateString = "2周前";
  284. } else if (days > 21 && days <= 30) {
  285. dateString = "3周前";
  286. } else if (days > 30) {
  287. dateString = "1月前";
  288. } else if (days > 365) {
  289. dateString = "1年前";
  290. } else if (days > 365 * 3) {
  291. dateString = "3年前";
  292. }
  293. return dateString;
  294. }
  295. /**
  296. * 比较两个时间相差分钟数
  297. *
  298. * @param now 当前时间
  299. * @param compareDate 比较时间
  300. * @return 相差分钟数
  301. */
  302. public static int compareMinutes(Date now, Date compareDate) {
  303. return (int) (now.getTime() - compareDate.getTime()) / 60000;
  304. }
  305. /**
  306. * 比较时间是本月的第几天
  307. *
  308. * @param date
  309. * @return
  310. */
  311. public static int getDayOfMonth(Date date) {
  312. DateTime dateTime = new DateTime(date);
  313. return dateTime.getDayOfMonth();
  314. }
  315. /**
  316. * 计算当月有几天
  317. *
  318. * @param date
  319. * @return
  320. */
  321. public static int getDateOfMonth(Date date) {
  322. DateTime dateTime = new DateTime(date);
  323. return dateTime.dayOfMonth().getMaximumValue();
  324. }
  325. /**
  326. * 指定时间,判断该时间到现在时间的年数
  327. *
  328. * @param date 指定时间
  329. * @return 到现在时间的年数
  330. */
  331. public static int compareYear(Date date) {
  332. DateTime btd = new DateTime(date);
  333. DateTime nowDate = new DateTime();
  334. int year = 0;
  335. if (nowDate.getMonthOfYear() > btd.getMonthOfYear()) {
  336. year = nowDate.getYear() - btd.getYear();
  337. } else if (nowDate.getMonthOfYear() < btd.getMonthOfYear()) {
  338. year = nowDate.getYear() - btd.getYear() - 1;
  339. } else if (nowDate.getMonthOfYear() == btd.getMonthOfYear()) {
  340. if (nowDate.getDayOfMonth() >= btd.getDayOfMonth()) {
  341. year = nowDate.getYear() - btd.getYear();
  342. } else {
  343. year = nowDate.getYear() - btd.getYear() - 1;
  344. }
  345. }
  346. return year;
  347. }
  348. /**
  349. * 判断2个时间的时间差 返回字符串形式
  350. *
  351. * @param date 要对比的字符串
  352. * @param date2 要对比的字符串
  353. * @return 字符串形式 如1小时 ,2天2小时
  354. */
  355. public static String compareDaysWithDate(Date date, Date date2) {
  356. StringBuilder msg = new StringBuilder();
  357. int minutes = (int) Math.abs((date.getTime() - date2.getTime()) / 60000);
  358. if (minutes / 60 > 0 && minutes / 60 / 24 <= 0) {
  359. msg.append(minutes / 60 + "小时");
  360. }
  361. if (minutes / 60 / 24 > 0) {
  362. msg.append(minutes / 60 / 24 + "天");
  363. msg.append(minutes / 60 % 24 + "小时");
  364. }
  365. return msg.toString();
  366. }
  367. public static final String REG_EXP_DATE = "^((([0-9]{3}[1-9]|[0-9]{2}[1-9][0-9]{1}|[0-9]{1}[1-9][0-9]{2}|[1-9][0-9]{3})-(((0[13578]|1[02])-(0[1-9]|[12][0-9]|3[01]))|((0[469]|11)-(0[1-9]|[12][0-9]|30))|(02-(0[1-9]|[1][0-9]|2[0-8]))))|((([0-9]{2})(0[48]|[2468][048]|[13579][26])|((0[48]|[2468][048]|[3579][26])00))-02-29))\\s+([0-1]?[0-9]|2[0-3]):([0-5][0-9]):([0-5][0-9])$";
  368. /**
  369. * 自动解析多种格式的时间字符串为时间对象<br>
  370. * 支持格式为:yyyy-MM-dd HH:mm:ss 支持多种分隔符,以及多种日期精度。 如yyyy年MM月。 HH时mm分ss秒
  371. * 已有更好的替代方案: {@link org.hsweb.commons.time.DateFormatter#fromString(String)}
  372. *
  373. * @param dateString 时间字符串 <br>
  374. * @return 格式正确则返回对应的java.util.Date对象 格式错误返回null
  375. */
  376. @Deprecated
  377. public static Date formatUnknownString2Date(String dateString) {
  378. try {
  379. if (StringUtils.isNullOrEmpty(dateString)) {
  380. return null;
  381. }
  382. dateString = dateString.replace("T", " ");
  383. String hms = "00:00:00";
  384. dateString = dateString.trim();
  385. if (dateString.contains(" ")) {
  386. // 截取时分秒
  387. hms = dateString.substring(dateString.indexOf(" ") + 1, dateString.length());
  388. // 重置日期
  389. dateString = dateString.substring(0, dateString.indexOf(" "));
  390. // 多中分隔符的支持
  391. hms = hms.replace(":", ":");
  392. hms = hms.replace("时", ":");
  393. hms = hms.replace("分", ":");
  394. hms = hms.replace("秒", ":");
  395. hms = hms.replace("-", ":");
  396. hms = hms.replace("-", ":");
  397. // 时间不同精确度的支持
  398. if (hms.endsWith(":")) {
  399. hms = hms.substring(0, hms.length() - 1);
  400. }
  401. if (hms.split(":").length == 1) {
  402. hms += ":00:00";
  403. }
  404. if (hms.split(":").length == 2) {
  405. hms += ":00";
  406. }
  407. }
  408. String[] hmsarr = hms.split(":");
  409. // 不同日期分隔符的支持
  410. dateString = dateString.replace(".", "-");
  411. dateString = dateString.replace("/", "-");
  412. dateString = dateString.replace("-", "-");
  413. dateString = dateString.replace("年", "-");
  414. dateString = dateString.replace("月", "-");
  415. dateString = dateString.replace("日", "");
  416. // 切割年月日
  417. String yearStr, monthStr, dateStr;
  418. // 截取日期
  419. String[] ymd = dateString.split("-");
  420. // 判断日期精确度
  421. yearStr = ymd[0];
  422. monthStr = ymd.length > 1 ? ymd[1] : "";
  423. dateStr = ymd.length > 2 ? ymd[2] : "";
  424. monthStr = monthStr == "" ? Integer.toString(1) : monthStr;
  425. dateStr = dateStr == "" ? Integer.toString(1) : dateStr;
  426. String dtr = (yearStr + "-" + formatDateSplit(monthStr) + "-" + formatDateSplit(dateStr) + " " + hms);
  427. if (!dtr.matches(REG_EXP_DATE))
  428. return null;
  429. // 返回日期
  430. return new DateTime(Integer.parseInt(yearStr.trim()), Integer.parseInt(monthStr.trim()), Integer.parseInt(dateStr.trim()), Integer.parseInt(hmsarr[0].trim()), Integer.parseInt(hmsarr[1].trim()), Integer.parseInt(hmsarr[2].trim()), 0).toDate();
  431. } catch (Exception e) {
  432. return null;
  433. }
  434. }
  435. private static String formatDateSplit(String md) {
  436. if (StringUtils.isInt(md)) {
  437. if (StringUtils.toInt(md) < 10) return "0".concat(String.valueOf(StringUtils.toInt(md)));
  438. }
  439. return md;
  440. }
  441. /**
  442. * 解析多个时间,指定时间之间的分隔符和时间的格式符 分隔符不能与格式符相同
  443. *
  444. * @param dateString 传入一个时间段字符串
  445. * @param spaceChar 指定格式符
  446. * @param splitChar 指定分隔符
  447. * @return 格式正确返回分割后的时间对象数组 格式错误返回null <br>
  448. * 指定了格式符为. 分隔符为- 返回值为 时间长度为2的Date类型数组<br>
  449. * 时间转换的方式详见 {@link DateTimeUtils#formatUnknownString2Date(String dateString)}
  450. */
  451. public static Date[] formatDatesByString(String dateString, String spaceChar, String splitChar) {
  452. if (spaceChar.equals(splitChar)) {
  453. return null;
  454. }
  455. String[] dateStrs = dateString.split(splitChar);
  456. Date[] dates = new Date[dateStrs.length];
  457. for (int i = 0, size = dateStrs.length; i < size; i++) {
  458. dates[i] = formatUnknownString2Date(dateStrs[i]);
  459. }
  460. return dates;
  461. }
  462. /**
  463. * 身份证号转生日
  464. *
  465. * @param identityCard 身份证
  466. * @return 生日
  467. */
  468. public static Date identityCard2Date(String identityCard) {
  469. try {
  470. String dateStr;
  471. if (identityCard.length() == 18) {
  472. dateStr = identityCard.substring(6, 14);// 截取18位身份证身份证中生日部分
  473. return formatDateString(dateStr, "yyyyMMdd");
  474. }
  475. if (identityCard.length() == 15) {
  476. dateStr = identityCard.substring(6, 12);// 截取15位身份证中生日部分
  477. return formatDateString(dateStr, "yyMMdd");
  478. }
  479. return null;
  480. } catch (Exception e) {
  481. return null;
  482. }
  483. }
  484. public static boolean validDate(String str) {
  485. try {
  486. Date date = formatUnknownString2Date(str);
  487. return date != null;
  488. } catch (Exception e) {
  489. return false;
  490. }
  491. }
  492. }