几个日期时间工具类

港控/mmm° 2023-10-05 15:58 125阅读 0赞

参考:

https://www.jianshu.com/p/b79f52c1aab2

https://www.jianshu.com/p/ffd5f3541f21

  1. package com.wanggs.utils;
  2. import java.text.SimpleDateFormat;
  3. import java.util.Calendar;
  4. import java.util.Date;
  5. public class DateUtil {
  6. /**
  7. * 获取两个时间之间的天数
  8. * @param maxDate 大的日期
  9. * @param minDate 小的日期
  10. * @return
  11. * @throws Exception
  12. */
  13. public static int getDay(Date maxDate,Date minDate) throws Exception {
  14. int day = 0;
  15. SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
  16. minDate=sdf.parse(sdf.format(minDate));
  17. maxDate=sdf.parse(sdf.format(maxDate));
  18. Calendar cal = Calendar.getInstance();
  19. cal.setTime(minDate);
  20. long time1 = cal.getTimeInMillis();
  21. cal.setTime(maxDate);
  22. long time2 = cal.getTimeInMillis();
  23. long between_days=(time2-time1)/(1000*3600*24);
  24. if (between_days>0) {
  25. day = Integer.parseInt(String.valueOf(between_days));
  26. }
  27. return day;
  28. }
  29. /**
  30. * 由出生日期获得年龄
  31. *
  32. * @param birthDay
  33. * @return
  34. * @throws Exception
  35. */
  36. public static int getAge(Date birthDay) throws Exception {
  37. Calendar cal = Calendar.getInstance();
  38. if (cal.before(birthDay)) {
  39. throw new IllegalArgumentException("The birthDay is before Now.It's unbelievable!");
  40. }
  41. //获取当前年
  42. int yearNow = cal.get(Calendar.YEAR);
  43. //获取当前月
  44. int monthNow = cal.get(Calendar.MONTH);
  45. //获取当日
  46. int dayOfMonthNow = cal.get(Calendar.DAY_OF_MONTH);
  47. cal.setTime(birthDay);
  48. //获取出生那年
  49. int yearBirth = cal.get(Calendar.YEAR);
  50. //获取出生月
  51. int monthBirth = cal.get(Calendar.MONTH);
  52. //获取出生日
  53. int dayOfMonthBirth = cal.get(Calendar.DAY_OF_MONTH);
  54. //年纪
  55. int age = yearNow - yearBirth;
  56. //如果现在的月份小于生日的月份,年龄-1,如果等于出生的月份,日前小于生日日期,年龄-1
  57. if (monthNow <= monthBirth) {
  58. if (monthNow == monthBirth) {
  59. if (dayOfMonthNow < dayOfMonthBirth)
  60. age--;
  61. } else {
  62. age--;
  63. }
  64. }
  65. return age;
  66. }
  67. }
  68. package com.wanggs.utils;
  69. import java.text.DateFormat;
  70. import java.text.ParseException;
  71. import java.text.SimpleDateFormat;
  72. import java.util.Calendar;
  73. import java.util.Date;
  74. import java.util.Hashtable;
  75. import java.util.Map;
  76. /**
  77. * 日期处理工具,线程安全
  78. */
  79. public class DateUtils {
  80. private static Map<String, ThreadLocal<DateFormat>> thredlocalmap = new Hashtable<String, ThreadLocal<DateFormat>>();
  81. public static final String yyyyMMddHHmmss = "yyyy-MM-dd HH:mm:ss";
  82. public static final String yyyyMMdd = "yyyy-MM-dd";
  83. public static final String yyyyMM = "yyyy-MM";
  84. public static final String yyyy = "yyyy";
  85. public static final String HHmmss = "HH:mm:ss";
  86. public static final String MM = "MM";
  87. public static final String week = "E";
  88. static {
  89. thredlocalmap.put(yyyyMMddHHmmss, new ThreadLocal<DateFormat>());
  90. thredlocalmap.put(yyyyMMdd, new ThreadLocal<DateFormat>());
  91. thredlocalmap.put(yyyyMM, new ThreadLocal<DateFormat>());
  92. thredlocalmap.put(yyyy, new ThreadLocal<DateFormat>());
  93. thredlocalmap.put(HHmmss, new ThreadLocal<DateFormat>());
  94. thredlocalmap.put(MM, new ThreadLocal<DateFormat>());
  95. thredlocalmap.put(week, new ThreadLocal<DateFormat>());
  96. }
  97. /**
  98. * 通过格式获取格式化对象,线程安全
  99. *
  100. * @param datePattern
  101. * @return
  102. */
  103. public static DateFormat getDateFormat(String datePattern) {
  104. ThreadLocal<DateFormat> threadlocal = getThreadLocal(datePattern);
  105. DateFormat fmt = threadlocal.get();
  106. if (fmt == null) {
  107. fmt = new SimpleDateFormat(datePattern);
  108. threadlocal.set(fmt);
  109. }
  110. return fmt;
  111. }
  112. private static ThreadLocal<DateFormat> getThreadLocal(String datePattern) {
  113. ThreadLocal<DateFormat> theadlocal = thredlocalmap.get(datePattern);
  114. if(theadlocal == null) {
  115. theadlocal = new ThreadLocal<DateFormat>();
  116. thredlocalmap.put(datePattern, theadlocal);
  117. }
  118. return theadlocal;
  119. }
  120. /**
  121. * 将字符串日期转换成Date对象
  122. *
  123. * @param dateStr 日期字符串
  124. * @param datePattern 日期格式
  125. * @return
  126. */
  127. public static Date parse(String dateStr, String datePattern) {
  128. try {
  129. return getDateFormat(datePattern).parse(dateStr);
  130. } catch (ParseException e) {
  131. e.printStackTrace();
  132. return null;
  133. }
  134. }
  135. /**
  136. * 将Date对象转换成字符串日期
  137. *
  138. * @param date 日期对象
  139. * @param datePattern 日期格式
  140. * @return
  141. */
  142. public static String format(Date date, String datePattern) {
  143. return getDateFormat(datePattern).format(date);
  144. }
  145. /**
  146. * 取得特定时间对应的字符串,格式化为yyyy-MM-dd HH:mm:ss
  147. *
  148. * @param date 日期对象
  149. * @return
  150. */
  151. public static String ymdhmsFormat(Date date) {
  152. return format(date, yyyyMMddHHmmss);
  153. }
  154. /**
  155. * 取得特定时间对应的字符串,格式化为yyyy-MM-dd
  156. *
  157. * @param date
  158. * @return
  159. */
  160. public static String ymdFormat(Date date) {
  161. return format(date, yyyyMMdd);
  162. }
  163. /**
  164. * 根据当前日期,得到当前年月
  165. *
  166. * @param date
  167. * @return str
  168. */
  169. public static final String ymFormat(Date date) {
  170. if (date == null)
  171. return "";
  172. return format(date, yyyyMM);
  173. }
  174. /**
  175. * 根据当前日期,得到当前年份
  176. *
  177. * @param date
  178. * @return str
  179. */
  180. public static final String yFormat(Date date) {
  181. if (date == null)
  182. return "";
  183. return format(date, yyyy);
  184. }
  185. /**
  186. * 根据当前日期,得到当前月份
  187. *
  188. * @param date
  189. * @return str
  190. */
  191. public static final String mFormat(Date date) {
  192. if (date == null)
  193. return "";
  194. return format(date, MM);
  195. }
  196. /**
  197. * 返回当前的时间,格式为H:mm:ss
  198. *
  199. * @return 时间字符串
  200. */
  201. public static final String getTimeNow() {
  202. return format(new Date(), HHmmss);
  203. }
  204. /**
  205. * 把字符串形式转换成日期形式,字符串的格式必须为yyyy-MM-dd
  206. *
  207. * @param ymdStringDate
  208. * @return date
  209. */
  210. public static final Date ymdString2Date(String ymdStringDate) {
  211. if (ymdStringDate == null)
  212. return null;
  213. return parse(ymdStringDate, yyyyMMdd);
  214. }
  215. /**
  216. * 把字符串形式转换成日期形式,字符串的格式必须为yyyy-MM-dd HH:mm:ss
  217. *
  218. * @param ymdhmsStringDate
  219. * @return date
  220. */
  221. public static final Date ymdhmsString2Date(String ymdhmsStringDate) {
  222. if (ymdhmsStringDate == null)
  223. return null;
  224. return parse(ymdhmsStringDate, yyyyMMddHHmmss);
  225. }
  226. /**
  227. *
  228. * 得到当前时间,把日期后的时间归0 变成(yyyy-MM-dd 00:00:00:000)
  229. *
  230. * @return date
  231. */
  232. public static Date getCurrentDate() {
  233. Date date = new Date();
  234. return zerolizedTime(date);
  235. }
  236. /**
  237. * 把日期后的时间归0 变成(yyyy-MM-dd 00:00:00:000)
  238. *
  239. * @param fullDate
  240. * @return Date
  241. */
  242. public static final Date zerolizedTime(Date fullDate) {
  243. Calendar cal = Calendar.getInstance();
  244. cal.setTime(fullDate);
  245. cal.set(Calendar.HOUR_OF_DAY, 0);
  246. cal.set(Calendar.MINUTE, 0);
  247. cal.set(Calendar.SECOND, 0);
  248. cal.set(Calendar.MILLISECOND, 0);
  249. return cal.getTime();
  250. }
  251. /**
  252. * 得到两个时间的间隔
  253. *
  254. * @param bDate
  255. * @param eDate
  256. * @return
  257. */
  258. static public long dateDiffByDay(Date bDate, Date eDate) {
  259. if (bDate == null || eDate == null)
  260. return 0L;
  261. return (bDate.getTime() - eDate.getTime()) / (1000 * 3600 * 24);
  262. }
  263. /**
  264. * 取得指定日期的星期数
  265. *
  266. * @return String
  267. */
  268. public static final String getWeek(Date date) {
  269. if (date == null)
  270. return null;
  271. return format(date, week);
  272. }
  273. /**
  274. * 判断两个日期字符串是否相等,格式必需为yyyy-MM-dd
  275. *
  276. * @param one
  277. * 第一个日期字符串
  278. * @param two
  279. * 第二个日期字符串
  280. * @return Boolean
  281. */
  282. public static final boolean isEqual(String one, String two) {
  283. return ymdString2Date(one).equals(ymdString2Date(two));
  284. }
  285. /**
  286. * 判断两个日期字符串是否相等
  287. *
  288. * @param one
  289. * 第一个日期字符串
  290. * @param two
  291. * 第二个日期字符串
  292. * @param datePattern
  293. * 包含日期格式的字符串
  294. * @return Boolean
  295. */
  296. public static final boolean isEqual(String one, String two, String datePattern) {
  297. return isEqual(one, two, datePattern, datePattern);
  298. }
  299. /**
  300. * 判断两个日期字符串是否相等
  301. *
  302. * @param one
  303. * 第一个日期字符串
  304. * @param two
  305. * 第二个日期字符串
  306. * @param datePatternOne
  307. * 对应第一个日期字符串的包含日期格式的字符串
  308. * @param datePatternTwo
  309. * 对应第二个日期字符串的包含日期格式的字符串
  310. * @return Boolean
  311. */
  312. public static final Boolean isEqual(String one, String two,
  313. String datePatternOne, String datePatternTwo) {
  314. return parse(one, datePatternOne).equals(parse(two, datePatternTwo));
  315. }
  316. /**
  317. * 返回两时间的时间间隔(以分计算)
  318. *
  319. * @param date1
  320. * @param date2
  321. * @return
  322. */
  323. static public long spaceMinute(Date date1, Date date2) {
  324. Long num1 = date1.getTime();
  325. Long num2 = date2.getTime();
  326. Long space = (num2 - num1) / (1000 * 60);
  327. return space;
  328. }
  329. /**
  330. * 返回两时间的时间间隔(以天计算)
  331. *
  332. * @paramtime1
  333. * @paramtime2
  334. * @return
  335. */
  336. static public Long spaceDay(Date date1, Date date2) {
  337. Long num1 = date1.getTime();
  338. Long num2 = date2.getTime();
  339. Long space = (num2 - num1) / (1000 * 3600 * 24);
  340. return space;
  341. }
  342. static public Date getDateAfterDay(Date somedate, int day) {
  343. if (somedate == null)
  344. return null;
  345. Calendar cal = Calendar.getInstance();
  346. cal.setTime(somedate);
  347. cal.add(Calendar.DAY_OF_MONTH, day);
  348. return new Date(cal.getTime().getTime());
  349. }
  350. static public Date getDateAfterDay(int day) {
  351. Calendar cal = Calendar.getInstance();
  352. cal.setTime(new Date());
  353. cal.add(Calendar.DAY_OF_MONTH, day);
  354. return cal.getTime();
  355. }
  356. static public Date getTSAfterDay(Date somedate, int day) {
  357. Calendar cal = Calendar.getInstance();
  358. cal.setTime(somedate);
  359. cal.add(Calendar.DAY_OF_MONTH, day);
  360. return cal.getTime();
  361. }
  362. // 取得本月第一天时间
  363. static public Date getFirstDayOfMonth(Date date) {
  364. Calendar cal = Calendar.getInstance();
  365. cal.setTime(date);
  366. cal.set(Calendar.DAY_OF_MONTH, 1);
  367. return cal.getTime();
  368. }
  369. }
  370. package com.toltech.springboot.util;
  371. import org.apache.commons.lang3.StringUtils;
  372. import org.slf4j.Logger;
  373. import org.slf4j.LoggerFactory;
  374. import java.math.BigDecimal;
  375. import java.text.ParseException;
  376. import java.text.SimpleDateFormat;
  377. import java.util.Calendar;
  378. import java.util.Date;
  379. import java.util.GregorianCalendar;
  380. /**
  381. * 日期工具类,提供时间转换、比较、格式化等各种常用方法
  382. * @modificationHistory.
  383. * <ul>
  384. * <li>gaozhanglei 2010-8-27下午04:06:10 TODO</li>
  385. * <li>
  386. * sunju 2012-7-31 下午03:06:05 新增getDate方法,
  387. * 修改getNowDate方法以及其它几个使用了toLocaleString()的方法,解决Linux下时间错误问题
  388. * </li>
  389. * </ul>
  390. */
  391. public class DateUtil {
  392. private static Logger LOG = LoggerFactory.getLogger(DateUtil.class);
  393. /**
  394. * 时间间隔:日
  395. */
  396. public final static int DATE_INTERVAL_DAY = 1;
  397. /**
  398. * 时间间隔:周
  399. */
  400. public final static int DATE_INTERVAL_WEEK = 2;
  401. /**
  402. * 时间间隔:月
  403. */
  404. public final static int DATE_INTERVAL_MONTH = 3;
  405. /**
  406. * 时间间隔:年
  407. */
  408. public final static int DATE_INTERVAL_YEAR = 4;
  409. /**
  410. * 时间间隔:小时
  411. */
  412. public final static int DATE_INTERVAL_HOUR = 5;
  413. /**
  414. * 时间间隔:分钟
  415. */
  416. public final static int DATE_INTERVAL_MINUTE = 6;
  417. /**
  418. * 时间间隔:秒
  419. */
  420. public final static int DATE_INTERVAL_SECOND = 7;
  421. /**
  422. * 时间格式:年月日
  423. */
  424. public final static String DATE_FORMAT_MDY = "MM/dd/yyyy";
  425. public final static String DATE_FORMAT_YMD = "yyyy-MM-dd";
  426. public final static String DATE_FORMAT_YMD_ZH = "yyyy年MM月 ";
  427. public final static String DATE_FORMAT_YMDHMS_ZH = "yyyy年MM月dd日 ";
  428. public final static String DATE_FORMATE_YM="yyyyMM";
  429. public final static String DATE_FORMATE_LC="yy年MM月";
  430. public final static String DATE_FORMAT_MD="MM-dd";
  431. public final static String DATE_FORMAT_YMD_NL="yyyyMMdd";
  432. /**
  433. * 时间格式:年月日时分秒
  434. */
  435. public final static String DATE_FORMAT_YMDHMS = "yyyy-MM-dd HH:mm:ss";
  436. public final static String DATE_FORMATE_LX_YMDHMS = "yyyyMMddHHmmss";
  437. public static final String DATE_FORMATE_LX_YMDHMSS = "mmss";
  438. /**
  439. * 获得时间
  440. * @author sunju
  441. * @creationDate. 2012-7-31 下午03:06:05
  442. * @param date 时间
  443. * @param dateFormat 时间格式
  444. * @return 时间
  445. */
  446. public static Date getDate(Date date, String dateFormat) {
  447. return parseDate(dateFormat(date, dateFormat), dateFormat);
  448. }
  449. /**
  450. * 获得当前日期(年月日)
  451. * @author sunju
  452. * @creationDate. 2010-8-27 下午05:11:23
  453. * @return 当前时间(yyyy-MM-dd)
  454. */
  455. public static Date getNowDate() {
  456. return parseDate(dateFormat(new Date(), DATE_FORMAT_YMD), DATE_FORMAT_YMD);
  457. }
  458. /**
  459. * 获取当前时间字符串(年月日)
  460. * @author sunju
  461. * @creationDate. 2011-5-4 下午08:22:34
  462. * @return 时间字符串
  463. */
  464. public static String getNowStringDate() {
  465. return dateFormat(new Date(), DATE_FORMAT_YMD);
  466. }
  467. /**
  468. * 获得当前时间(年月日时分秒)
  469. * @author sunju
  470. * @creationDate. 2010-8-27 下午05:12:57
  471. * @return 当前时间(yyyy-MM-dd HH:mm:ss)
  472. */
  473. public static Date getNowTime() {
  474. return parseDate(dateFormat(new Date(), DATE_FORMAT_YMDHMS), DATE_FORMAT_YMDHMS);
  475. }
  476. /**
  477. * 获取当前时间字符串(年月日时分秒)
  478. * @author sunju
  479. * @creationDate. 2014-3-10 下午03:16:42
  480. * @return 时间字符串
  481. */
  482. public static String getNowStringTime() {
  483. return dateFormat(new Date(), DATE_FORMAT_YMDHMS);
  484. }
  485. /**
  486. * 获得明天的日期字符串(格式年月日)
  487. * @author sunju
  488. * @creationDate. 2011-5-4 下午08:19:28
  489. * @return 明天的日期
  490. */
  491. public static String getTomorrowStringDate() {
  492. return dateFormat(getTomorrowTime(), DATE_FORMAT_YMD);
  493. }
  494. /**
  495. * 获得明天的日期(年月日)
  496. * @author sunju
  497. * @creationDate. 2011-5-4 下午08:19:57
  498. * @return 明天的日期
  499. */
  500. public static Date getTomorrowDate() {
  501. return dateAdd(DATE_INTERVAL_DAY, getNowDate(), 1);
  502. }
  503. /**
  504. * 获得明天的时间(年月日时分秒)
  505. * @author sunju
  506. * @creationDate. 2011-5-4 下午08:20:19
  507. * @return 明天的时间
  508. */
  509. public static Date getTomorrowTime() {
  510. return dateAdd(DATE_INTERVAL_DAY, getNowTime(), 1);
  511. }
  512. /**
  513. * 获得昨天的日期
  514. * @author sunju
  515. * @creationDate. 2013-10-22 下午03:54:48
  516. * @return 昨天的日期
  517. */
  518. public static Date getYesterdayDate() {
  519. return dateAdd(DATE_INTERVAL_DAY, getNowDate(), -1);
  520. }
  521. /**
  522. * 获得昨天的时间(年月日时分秒)
  523. * @author sunju
  524. * @creationDate. 2013-10-22 下午03:54:48
  525. * @return 昨天的日期
  526. */
  527. public static Date getYseterdayTime(){
  528. return dateAdd(DATE_INTERVAL_DAY, getNowTime(), -1);
  529. }
  530. /**
  531. * 获取当月第一天
  532. * @author sunju
  533. * @creationDate. 2013-10-22 下午03:45:53
  534. * @return 日期
  535. */
  536. public static Date getMonthFirst() {
  537. Calendar lastDate = Calendar.getInstance();
  538. lastDate.set(Calendar.DATE, 1); // 设为当前月的1号
  539. return getDate(lastDate.getTime(), DATE_FORMAT_YMD);
  540. }
  541. /**
  542. * 获得下个月第一天的日期
  543. * @author sunju
  544. * @creationDate. 2013-10-22 下午03:52:38
  545. * @return 日期
  546. */
  547. public static Date getNextMonthFirst() {
  548. Calendar lastDate = Calendar.getInstance();
  549. lastDate.add(Calendar.MONTH, 1); // 加一个月
  550. lastDate.set(Calendar.DATE, 1); // 把日期设置为当月第一天
  551. return getDate(lastDate.getTime(), DATE_FORMAT_YMD);
  552. }
  553. public static Date getMonthStartTime(Date date, int monthDiff){
  554. Calendar calendar = GregorianCalendar.getInstance();
  555. if(date != null){
  556. calendar.setTime(date);
  557. }else{
  558. calendar.setTimeInMillis(System.currentTimeMillis());
  559. }
  560. if(monthDiff != 0){
  561. calendar.add(Calendar.MONTH, monthDiff);
  562. }
  563. calendar.set(Calendar.DAY_OF_MONTH, 1);
  564. calendar.set(Calendar.HOUR_OF_DAY, 0);
  565. calendar.set(Calendar.MINUTE, 0);
  566. calendar.set(Calendar.SECOND, 0);
  567. calendar.set(Calendar.MILLISECOND, 0);
  568. Date resultDate = calendar.getTime();
  569. return resultDate;
  570. }
  571. public static Date getMonthEndTime(Date date, int monthDiff){
  572. Calendar calendar = GregorianCalendar.getInstance();
  573. if(date != null){
  574. calendar.setTime(date);
  575. }else{
  576. calendar.setTimeInMillis(System.currentTimeMillis());
  577. }
  578. if(monthDiff != 0){
  579. calendar.add(Calendar.MONTH, monthDiff);
  580. }
  581. calendar.set(Calendar.DAY_OF_MONTH, calendar.getActualMaximum(Calendar.DAY_OF_MONTH));
  582. calendar.set(Calendar.HOUR_OF_DAY, 23);
  583. calendar.set(Calendar.MINUTE, 59);
  584. calendar.set(Calendar.SECOND, 59);
  585. calendar.set(Calendar.MILLISECOND, 999);
  586. Date resultDate = calendar.getTime();
  587. return resultDate;
  588. }
  589. /**
  590. * 取得当前星期几
  591. * @author sunju
  592. * @creationDate. 2010-9-20 下午05:34:36
  593. * @param date 时间
  594. * @return 星期
  595. */
  596. public static String getWeekOfDate(Date date) {
  597. if (date == null) {
  598. return null;
  599. }
  600. String[] weekDays = {"星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六"};
  601. Calendar cal = Calendar.getInstance();
  602. cal.setTime(date);
  603. int w = cal.get(Calendar.DAY_OF_WEEK) - 1;
  604. if (w < 0) {
  605. w = 0;
  606. }
  607. return weekDays[w];
  608. }
  609. /**
  610. * 时间类型转换返回字符串
  611. * @author sunju
  612. * @creationDate. 2010-8-27 下午05:18:37
  613. * @param date 时间
  614. * @param dateFormat 时间格式
  615. * @return 转换后的时间字符串
  616. */
  617. public static String dateFormat(Date date, String dateFormat) {
  618. if (date == null) {
  619. return null;
  620. }
  621. SimpleDateFormat format = new SimpleDateFormat(dateFormat);
  622. return format.format(date);
  623. }
  624. /**
  625. * 字符串时间类型转换返回Date类型
  626. * @author sunju
  627. * @creationDate. 2010-8-27 下午05:23:35
  628. * @param date 字符串时间
  629. * @param dateFormat 时间格式
  630. * @return 转换后的时间
  631. */
  632. public static Date parseDate(String date, String dateFormat) {
  633. if (StringUtils.isEmpty(date)) {
  634. return null;
  635. }
  636. SimpleDateFormat format = new SimpleDateFormat(dateFormat);
  637. try {
  638. return format.parse(date);
  639. } catch (Exception e) {
  640. LOG.error(e.getMessage());
  641. return null;
  642. }
  643. }
  644. public static Date getDateStartTime(Date date){
  645. Calendar calendar = GregorianCalendar.getInstance();
  646. if(date != null){
  647. calendar.setTime(date);
  648. }else{
  649. calendar.setTimeInMillis(System.currentTimeMillis());
  650. }
  651. calendar.set(Calendar.HOUR_OF_DAY, 0);
  652. calendar.set(Calendar.MINUTE, 0);
  653. calendar.set(Calendar.SECOND, 0);
  654. calendar.set(Calendar.MILLISECOND, 0);
  655. Date resultDate = calendar.getTime();
  656. return resultDate;
  657. }
  658. public static Date getDateEndTime(Date date){
  659. Calendar calendar = GregorianCalendar.getInstance();
  660. if(date != null){
  661. calendar.setTime(date);
  662. }else{
  663. calendar.setTimeInMillis(System.currentTimeMillis());
  664. }
  665. calendar.set(Calendar.HOUR_OF_DAY, 23);
  666. calendar.set(Calendar.MINUTE, 59);
  667. calendar.set(Calendar.SECOND, 59);
  668. calendar.set(Calendar.MILLISECOND, 999);
  669. Date resultDate = calendar.getTime();
  670. return resultDate;
  671. }
  672. /**
  673. * 加时间
  674. * @author sunju
  675. * @creationDate. 2010-8-27 下午05:28:06
  676. * @param interval 增加项,可以是天数、月份、年数、时间、分钟、秒
  677. * @param date 时间
  678. * @param num 加的数目
  679. * @return 时间加后的时间
  680. */
  681. public static Date dateAdd(int interval, Date date, int num) {
  682. if (date == null) {
  683. return null;
  684. }
  685. Calendar calendar = Calendar.getInstance();
  686. calendar.setTime(date);
  687. switch (interval) {
  688. case DATE_INTERVAL_DAY:
  689. calendar.add(Calendar.DATE, num);
  690. break;
  691. case DATE_INTERVAL_WEEK:
  692. calendar.add(Calendar.WEEK_OF_MONTH, num);
  693. break;
  694. case DATE_INTERVAL_MONTH:
  695. calendar.add(Calendar.MONTH, num);
  696. break;
  697. case DATE_INTERVAL_YEAR:
  698. calendar.add(Calendar.YEAR, num);
  699. break;
  700. case DATE_INTERVAL_HOUR:
  701. calendar.add(Calendar.HOUR, num);
  702. break;
  703. case DATE_INTERVAL_MINUTE:
  704. calendar.add(Calendar.MINUTE, num);
  705. break;
  706. case DATE_INTERVAL_SECOND:
  707. calendar.add(Calendar.SECOND, num);
  708. break;
  709. default:
  710. }
  711. return calendar.getTime();
  712. }
  713. /**
  714. * 两个时间时间差[前面时间和比较时间比,小于比较时间返回负数]
  715. * @author sunju
  716. * @creationDate. 2010-8-27 下午05:26:13
  717. * @param interval 比较项,可以是天数、月份、年数、时间、分钟、秒
  718. * @param date 时间
  719. * @param compare 比较的时间
  720. * @return 时间差(保留两位小数点,小数点以后两位四舍五入)
  721. */
  722. public static double getDateDiff(int interval, Date date, Date compare) {
  723. if (date == null || compare == null) {
  724. return 0;
  725. }
  726. double result = 0;
  727. double time = 0;
  728. Calendar calendar = null;
  729. switch (interval) {
  730. case DATE_INTERVAL_DAY:
  731. time = date.getTime() - compare.getTime();
  732. result = time / 1000d / 60d / 60d / 24d;
  733. break;
  734. case DATE_INTERVAL_HOUR:
  735. time = date.getTime() - compare.getTime();
  736. result = time / 1000d / 60d / 60d;
  737. break;
  738. case DATE_INTERVAL_MINUTE:
  739. time = date.getTime() / 1000d / 60d;
  740. result = time - compare.getTime() / 1000d / 60d;
  741. break;
  742. case DATE_INTERVAL_MONTH:
  743. calendar = Calendar.getInstance();
  744. calendar.setTime(date);
  745. time = calendar.get(Calendar.YEAR) * 12d;
  746. calendar.setTime(compare);
  747. time -= calendar.get(Calendar.YEAR) * 12d;
  748. calendar.setTime(date);
  749. time += calendar.get(Calendar.MONTH);
  750. calendar.setTime(compare);
  751. result = time - calendar.get(Calendar.MONTH);
  752. break;
  753. case DATE_INTERVAL_SECOND:
  754. time = date.getTime() - compare.getTime();
  755. result = time / 1000d;
  756. break;
  757. case DATE_INTERVAL_WEEK:
  758. calendar = Calendar.getInstance();
  759. calendar.setTime(date);
  760. time = calendar.get(Calendar.YEAR) * 52d;
  761. calendar.setTime(compare);
  762. time -= calendar.get(Calendar.YEAR) * 52d;
  763. calendar.setTime(date);
  764. time += calendar.get(Calendar.WEEK_OF_YEAR);
  765. calendar.setTime(compare);
  766. result = time - calendar.get(Calendar.WEEK_OF_YEAR);
  767. break;
  768. case DATE_INTERVAL_YEAR:
  769. calendar = Calendar.getInstance();
  770. calendar.setTime(date);
  771. time = calendar.get(Calendar.YEAR);
  772. calendar.setTime(compare);
  773. result = time - (double)calendar.get(Calendar.YEAR);
  774. break;
  775. default:
  776. break;
  777. }
  778. return new BigDecimal(result).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
  779. }
  780. /**
  781. * 获取时间差[前面时间和比较时间比,小于比较时间返回负数]
  782. * @author sunju
  783. * @creationDate. 2010-9-1 下午04:36:07
  784. * @param level 返回时间等级(1:返回天;2:返回天-小时;3:返回天-小时-分4:返回天-小时-分-秒;)
  785. * @param date 时间
  786. * @param compare 比较的时间
  787. * @return 时间差(保留两位小数点,小数点以后两位四舍五入)
  788. */
  789. public static String getDateBetween(Integer level, Date date, Date compare) {
  790. if (date == null || compare == null) {
  791. return null;
  792. }
  793. long s = new BigDecimal(getDateDiff(DATE_INTERVAL_SECOND, date, compare)).setScale(2, BigDecimal.ROUND_HALF_UP).longValue();
  794. int ss = 1;
  795. int mi = ss * 60;
  796. int hh = mi * 60;
  797. int dd = hh * 24;
  798. long day = s / dd;
  799. long hour = (s - day * dd) / hh;
  800. long minute = (s - day * dd - hour * hh) / mi;
  801. long second = (s - day * dd - hour * hh - minute * mi) / ss;
  802. String flag =(day < 0 || hour < 0 || minute < 0 || second < 0) ? "-" : "";
  803. day = Math.abs(day);
  804. hour = Math.abs(hour);
  805. minute = Math.abs(minute);
  806. second = Math.abs(second);
  807. StringBuilder result = new StringBuilder(flag);
  808. switch (level) {
  809. case 1:
  810. if (day != 0) {
  811. result.append(day).append("天");
  812. }
  813. break;
  814. case 2:
  815. if (day != 0) {
  816. result.append(day).append("天");
  817. }
  818. if (hour != 0) {
  819. result.append(hour).append("小时");
  820. }
  821. break;
  822. case 3:
  823. if (day != 0) {
  824. result.append(day).append("天");
  825. }
  826. if (hour != 0) {
  827. result.append(hour).append("小时");
  828. }
  829. if (minute != 0) {
  830. result.append(minute).append("分");
  831. }
  832. break;
  833. case 4:
  834. if (day != 0) {
  835. result.append(day).append("天");
  836. }
  837. if (hour != 0) {
  838. result.append(hour).append("小时");
  839. }
  840. if (minute != 0) {
  841. result.append(minute).append("分");
  842. }
  843. if (second != 0) {
  844. result.append(second).append("秒");
  845. }
  846. break;
  847. default:
  848. break;
  849. }
  850. return result.toString();
  851. }
  852. /**
  853. * 时间是否是今天
  854. * @author sunju
  855. * @creationDate. 2011-5-4 下午08:24:58
  856. * @param date 时间
  857. * @return 布尔
  858. */
  859. public static boolean isToday(Date date) {
  860. if (date == null) return false;
  861. return getNowStringDate().equals(dateFormat(date, DATE_FORMAT_YMD));
  862. }
  863. /**
  864. * 时间是否合法
  865. * @author sunju
  866. * @creationDate. 2012-6-19 下午01:07:59
  867. * @param date 时间
  868. * @param dateFormat 时间格式
  869. * @return
  870. */
  871. public static boolean isValidDate(String date, String dateFormat) {
  872. try {
  873. new SimpleDateFormat(dateFormat).parse(date);
  874. return true;
  875. } catch (Exception e) {
  876. return false;
  877. }
  878. }
  879. /**
  880. *
  881. * 是否大于现在的时间
  882. * true 大于
  883. * <ul>
  884. * <li>
  885. * <b>原因:<br/>
  886. * <p>
  887. * [2014-8-27]gaozhanglei<br/>
  888. * @param date
  889. * @param dateFormate
  890. * @return
  891. * TODO
  892. * </p>
  893. * </li>
  894. * </ul>
  895. */
  896. public static boolean isgtnow(String date,String dateFormate) {
  897. boolean flag=false;
  898. try {
  899. Date nowdt=new Date();
  900. Date compt=DateUtil.parseDate(date, dateFormate);
  901. long nowtm=nowdt.getTime();
  902. long comptm=compt.getTime();
  903. if(comptm > nowtm) {
  904. flag=true;
  905. }
  906. }catch (Exception e) {
  907. flag=false;
  908. }
  909. return flag;
  910. }
  911. /**
  912. * 得到本月的最后一天
  913. *
  914. * @return
  915. */
  916. public static String getMonthLastDay() {
  917. Calendar calendar = Calendar.getInstance();
  918. calendar.set(Calendar.DAY_OF_MONTH, calendar
  919. .getActualMaximum(Calendar.DAY_OF_MONTH));
  920. return dateFormat(calendar.getTime(),DATE_FORMAT_YMD);
  921. }
  922. /**
  923. * 获取时间在当月的天数
  924. * @param date
  925. * @return
  926. */
  927. public static int getDayOfMonth(Date date){
  928. Calendar calendar = Calendar.getInstance();
  929. calendar.setTime(date);
  930. return calendar.get(Calendar.DAY_OF_MONTH);
  931. }
  932. public static int getMaxDayOfMonth(Date date){
  933. Calendar calendar = Calendar.getInstance();
  934. calendar.setTime(date);
  935. return calendar.getActualMaximum(Calendar.DAY_OF_MONTH);
  936. }
  937. //当前时间转时间戳
  938. public static String timeStamp(){
  939. SimpleDateFormat format = new SimpleDateFormat(DATE_FORMAT_YMDHMS);
  940. String time="1970-01-06 11:45:55";
  941. String date =null;
  942. try {
  943. date = format.parse(time).toString();
  944. } catch (ParseException e) {
  945. }
  946. return date;
  947. }
  948. /**
  949. * 计算产品到期时间
  950. * @param productCycle 产品包周期值
  951. * @return 产品包到期时间
  952. */
  953. public static Date getDueTime(String productCycle){
  954. Date payTime = new Date(); //付费成功时间
  955. Calendar calendar = Calendar.getInstance();
  956. calendar.setTime(payTime);
  957. switch (productCycle) {
  958. case "0": // 包年
  959. calendar.add(Calendar.MONTH, 13);
  960. break;
  961. case "1": //包半年
  962. calendar.add(Calendar.MONTH, 7);
  963. break;
  964. case "2": //包季
  965. calendar.add(Calendar.MONTH, 4);
  966. break;
  967. case "3": //包月
  968. calendar.add(Calendar.MONTH, 1);
  969. break;
  970. case "4": //包天
  971. calendar.add(Calendar.DATE, 1);
  972. break;
  973. case "5": //单点
  974. calendar.add(Calendar.MONTH, 1);
  975. break;
  976. default:
  977. break;
  978. }
  979. return calendar.getTime();
  980. }
  981. /***
  982. * 用户产品包实际不可看时间(用于产品通知)
  983. * @param productCycle
  984. * @return
  985. */
  986. public static Date getActualDueTime(String productCycle){
  987. Date payTime = new Date(); //付费成功时间
  988. Calendar calendar = Calendar.getInstance();
  989. calendar.setTime(payTime);
  990. switch (productCycle) {
  991. case "0": // 包年
  992. calendar.add(Calendar.MONTH, 13);
  993. break;
  994. case "1": //包半年
  995. calendar.add(Calendar.MONTH, 7);
  996. break;
  997. case "2": //包季
  998. calendar.add(Calendar.MONTH, 4);
  999. break;
  1000. case "3": //包月
  1001. calendar.add(Calendar.MONTH, 1);
  1002. break;
  1003. case "4": //包天
  1004. calendar.add(Calendar.DATE, 1);
  1005. break;
  1006. case "5": //单点
  1007. calendar.add(Calendar.MONTH, 1);
  1008. break;
  1009. default:
  1010. break;
  1011. }
  1012. return calendar.getTime();
  1013. }
  1014. }
  1015. public class TimeUtil {
  1016. /**
  1017. *一些时间格式
  1018. */
  1019. public final static String FORMAT_TIME = "HH:mm";
  1020. public final static String FORMAT_DATE_TIME = "yyyy-MM-dd HH:mm";
  1021. public final static String FORMAT_DATE_TIME_SECOND = "yyyy-MM-dd HH:mm:ss";
  1022. public final static String FORMAT_MONTH_DAY_TIME = "MM-dd HH:mm";
  1023. public final static String FORMAT_DATE = "yyyy-MM-dd";
  1024. public static String getFormatToday(String dateFormat) {
  1025. Date currentTime = new Date();
  1026. SimpleDateFormat formatter = new SimpleDateFormat(dateFormat);
  1027. return formatter.format(currentTime);
  1028. }
  1029. public static Date stringToDate(String dateStr, String dateFormat) {
  1030. SimpleDateFormat formatter = new SimpleDateFormat(dateFormat);
  1031. try {
  1032. return formatter.parse(dateStr);
  1033. } catch (ParseException e) {
  1034. return null;
  1035. }
  1036. }
  1037. public static String dateToString(Date date, String dateFormat) {
  1038. SimpleDateFormat formatter = new SimpleDateFormat(dateFormat);
  1039. return formatter.format(date);
  1040. }
  1041. /**
  1042. *类似QQ/微信 聊天消息的时间
  1043. */
  1044. public static String getChatTime(boolean hasYear, long timesamp) {
  1045. long clearTime = timesamp;
  1046. String result;
  1047. SimpleDateFormat sdf = new SimpleDateFormat("dd");
  1048. Date today = new Date(System.currentTimeMillis());
  1049. Date otherDay = new Date(clearTime);
  1050. int temp = Integer.parseInt(sdf.format(today))
  1051. - Integer.parseInt(sdf.format(otherDay));
  1052. switch (temp) {
  1053. case 0:
  1054. result = "今天 " + getHourAndMin(clearTime);
  1055. break;
  1056. case 1:
  1057. result = "昨天 " + getHourAndMin(clearTime);
  1058. break;
  1059. case 2:
  1060. result = "前天 " + getHourAndMin(clearTime);
  1061. break;
  1062. default:
  1063. result = getTime(hasYear,clearTime);
  1064. break;
  1065. }
  1066. return result;
  1067. }
  1068. private static String getTime(boolean hasYear, long time) {
  1069. String pattern=FORMAT_DATE_TIME;
  1070. if(!hasYear){
  1071. pattern = FORMAT_MONTH_DAY_TIME;
  1072. }
  1073. SimpleDateFormat format = new SimpleDateFormat(pattern);
  1074. return format.format(new Date(time));
  1075. }
  1076. private static String getHourAndMin(long time) {
  1077. SimpleDateFormat format = new SimpleDateFormat(FORMAT_TIME);
  1078. return format.format(new Date(time));
  1079. }
  1080. /**
  1081. * 获取当前日期是星期几<br>
  1082. *
  1083. * @param date
  1084. * @return 当前日期是星期几
  1085. */
  1086. public static String getWeekOfDate(Date date) {
  1087. String[] weekDays = {"星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六"};
  1088. Calendar cal = Calendar.getInstance();
  1089. cal.setTime(date);
  1090. int w = cal.get(Calendar.DAY_OF_WEEK) - 1;
  1091. if (w < 0)
  1092. w = 0;
  1093. return weekDays[w];
  1094. }
  1095. }
  1096. /**
  1097. * 判断某个日期与今天相差 x年x天
  1098. * 如果大于1年,显示x年x天 。否则显示 x天
  1099. * @param timeStamp
  1100. * @return
  1101. */
  1102. public static String getOffsetYearAndDayByTimeStamp(long timeStamp) {
  1103. String result;
  1104. long currentTimeStamp = System.currentTimeMillis();
  1105. long targetTimestamp = timeStamp * 1000L;
  1106. int days = (int) ((currentTimeStamp - targetTimestamp) / ONE_YEAr);
  1107. if (days > 365) {
  1108. //大于1年
  1109. Calendar calendar1 = Calendar.getInstance();
  1110. calendar1.setTimeInMillis(currentTimeStamp);
  1111. Calendar calendar2 = Calendar.getInstance();
  1112. calendar2.setTimeInMillis(targetTimestamp);
  1113. //先判断是否同年
  1114. int y1 = calendar1.get(Calendar.YEAR);
  1115. int y2 = calendar2.get(Calendar.YEAR);
  1116. int d1 = calendar1.get(Calendar.DAY_OF_YEAR);
  1117. int d2 = calendar2.get(Calendar.DAY_OF_YEAR);
  1118. result = (y1 - y2) + "年" + (d1 - d2);
  1119. } else {
  1120. //不满一年,直接返回天数
  1121. result = String.valueOf(days);
  1122. }
  1123. return result;
  1124. }
  1125. /**
  1126. * 描述:计算两个日期所差的天数.
  1127. *
  1128. * @param date1 第一个时间的毫秒表示
  1129. * @param date2 第二个时间的毫秒表示
  1130. * @return int 所差的天数
  1131. */
  1132. public static int getOffsetDay(long date1, long date2) {
  1133. Calendar calendar1 = Calendar.getInstance();
  1134. calendar1.setTimeInMillis(date1);
  1135. Calendar calendar2 = Calendar.getInstance();
  1136. calendar2.setTimeInMillis(date2);
  1137. //先判断是否同年
  1138. int y1 = calendar1.get(Calendar.YEAR);
  1139. int y2 = calendar2.get(Calendar.YEAR);
  1140. int d1 = calendar1.get(Calendar.DAY_OF_YEAR);
  1141. int d2 = calendar2.get(Calendar.DAY_OF_YEAR);
  1142. int maxDays = 0;
  1143. int day = 0;
  1144. if (y1 - y2 > 0) {
  1145. maxDays = calendar2.getActualMaximum(Calendar.DAY_OF_YEAR);
  1146. day = d1 - d2 + maxDays;
  1147. } else if (y1 - y2 < 0) {
  1148. maxDays = calendar1.getActualMaximum(Calendar.DAY_OF_YEAR);
  1149. day = d1 - d2 - maxDays;
  1150. } else {
  1151. day = d1 - d2;
  1152. }
  1153. return day;
  1154. }
  1155. /**
  1156. * 描述:计算两个日期所差的小时数.
  1157. *
  1158. * @param date1 第一个时间的毫秒表示
  1159. * @param date2 第二个时间的毫秒表示
  1160. * @return int 所差的小时数
  1161. */
  1162. public static int getOffsetHour(long date1, long date2) {
  1163. Calendar calendar1 = Calendar.getInstance();
  1164. calendar1.setTimeInMillis(date1);
  1165. Calendar calendar2 = Calendar.getInstance();
  1166. calendar2.setTimeInMillis(date2);
  1167. int h1 = calendar1.get(Calendar.HOUR_OF_DAY);
  1168. int h2 = calendar2.get(Calendar.HOUR_OF_DAY);
  1169. int h = 0;
  1170. int day = getOffsetDay(date1, date2);
  1171. h = h1 - h2 + day * 24;
  1172. return h;
  1173. }
  1174. /**
  1175. * 描述:计算两个日期所差的分钟数.
  1176. *
  1177. * @param date1 第一个时间的毫秒表示
  1178. * @param date2 第二个时间的毫秒表示
  1179. * @return int 所差的分钟数
  1180. */
  1181. public static int getOffsetMinutes(long date1, long date2) {
  1182. Calendar calendar1 = Calendar.getInstance();
  1183. calendar1.setTimeInMillis(date1);
  1184. Calendar calendar2 = Calendar.getInstance();
  1185. calendar2.setTimeInMillis(date2);
  1186. int m1 = calendar1.get(Calendar.MINUTE);
  1187. int m2 = calendar2.get(Calendar.MINUTE);
  1188. int h = getOffsetHour(date1, date2);
  1189. int m = 0;
  1190. m = m1 - m2 + h * 60;
  1191. return m;
  1192. }
  1193. /**
  1194. * 描述:获取本周的某一天.
  1195. *
  1196. * @param format the format
  1197. * @param calendarField the calendar field
  1198. * @return String String类型日期时间
  1199. */
  1200. private static String getDayOfWeek(String format, int calendarField) {
  1201. String strDate = null;
  1202. try {
  1203. Calendar c = new GregorianCalendar();
  1204. SimpleDateFormat mSimpleDateFormat = new SimpleDateFormat(format);
  1205. int week = c.get(Calendar.DAY_OF_WEEK);
  1206. if (week == calendarField) {
  1207. strDate = mSimpleDateFormat.format(c.getTime());
  1208. } else {
  1209. int offectDay = calendarField - week;
  1210. if (calendarField == Calendar.SUNDAY) {
  1211. offectDay = 7 - Math.abs(offectDay);
  1212. }
  1213. c.add(Calendar.DATE, offectDay);
  1214. strDate = mSimpleDateFormat.format(c.getTime());
  1215. }
  1216. } catch (Exception e) {
  1217. e.printStackTrace();
  1218. }
  1219. return strDate;
  1220. }
  1221. /**
  1222. * 获取当前日期是星期几
  1223. *
  1224. * @param date
  1225. * @return 当前日期是星期几
  1226. */
  1227. public static String getWeekOfDate(Date date) {
  1228. String[] weekDays = {"星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六"};
  1229. Calendar cal = Calendar.getInstance();
  1230. cal.setTime(date);
  1231. int w = cal.get(Calendar.DAY_OF_WEEK) - 1;
  1232. if (w < 0)
  1233. w = 0;
  1234. return weekDays[w];
  1235. }
  1236. /**
  1237. * 描述:获取本月第一天.
  1238. *
  1239. * @param format the format
  1240. * @return String String类型日期时间
  1241. */
  1242. public static String getFirstDayOfMonth(String format) {
  1243. String strDate = null;
  1244. try {
  1245. Calendar c = new GregorianCalendar();
  1246. SimpleDateFormat mSimpleDateFormat = new SimpleDateFormat(format);
  1247. //当前月的第一天
  1248. c.set(GregorianCalendar.DAY_OF_MONTH, 1);
  1249. strDate = mSimpleDateFormat.format(c.getTime());
  1250. } catch (Exception e) {
  1251. e.printStackTrace();
  1252. }
  1253. return strDate;
  1254. }
  1255. /**
  1256. * 描述:获取本月最后一天.
  1257. *
  1258. * @param format the format
  1259. * @return String String类型日期时间
  1260. */
  1261. public static String getLastDayOfMonth(String format) {
  1262. String strDate = null;
  1263. try {
  1264. Calendar c = new GregorianCalendar();
  1265. SimpleDateFormat mSimpleDateFormat = new SimpleDateFormat(format);
  1266. // 当前月的最后一天
  1267. c.set(Calendar.DATE, 1);
  1268. c.roll(Calendar.DATE, -1);
  1269. strDate = mSimpleDateFormat.format(c.getTime());
  1270. } catch (Exception e) {
  1271. e.printStackTrace();
  1272. }
  1273. return strDate;
  1274. }

发表评论

表情:
评论列表 (有 0 条评论,125人围观)

还没有评论,来说两句吧...

相关阅读