1. import java.text.DateFormat;
  2. import java.text.ParseException;
  3. import java.text.SimpleDateFormat;
  4. import java.util.Calendar;
  5. import java.util.Date;
  6. import java.util.GregorianCalendar;
  7. import java.util.Locale;
  8. import java.util.MissingResourceException;
  9. import java.util.ResourceBundle;
  10.  
  11. import javax.xml.datatype.DatatypeConfigurationException;
  12. import javax.xml.datatype.DatatypeFactory;
  13. import javax.xml.datatype.XMLGregorianCalendar;
  14.  
  15. /**
  16. * Date Utility Class This is used to convert Strings to Dates and Timestamps
  17. * 格式约定
  18. * 字母 日期或时间元素 表示 示例
  19. * G Era 标志符 Text AD
  20. * y 年 Year 1996; 96
  21. * M 年中的月份 Month July; Jul; 07
  22. * w 年中的周数 Number 27
  23. * W 月份中的周数 Number 2
  24. * D 年中的天数 Number 189
  25. * d 月份中的天数 Number 10
  26. * F 月份中的星期 Number 2
  27. * a Am/pm 标记 Text PM
  28. * H 一天中的小时数(0-23) Number 0
  29. * k 一天中的小时数(1-24) Number 24
  30. * K am/pm 中的小时数(0-11) Number 0
  31. * h am/pm 中的小时数(1-12) Number 12
  32. * m 小时中的分钟数 Number 30
  33. * s 分钟中的秒数 Number 55
  34. * S 毫秒数 Number 978
  35. * z 时区 General time zone Pacific Standard Time; PST; GMT-08:00
  36. * Z 时区 RFC 822 time zone -0800
  37.  
  38. * StandardDate : [String][yyyy-MM-dd] 2015-01-05
  39. * StandardTime : [String][HH:mm:ss] 20:39:26
  40. * Standard : [String][yyyy-MM-dd HH:mm:ss] 2015-01-05 20:39:26
  41. * <p>
  42. * <a href="DateUtil.java.html"><i>View Source</i></a>
  43. * </p>
  44. *
  45. * @author <a href="mailto:xia_chaojun@newautovideo.com">chaojun xia</a> Minutes
  46. * should be mm not MM (MM is month).
  47. * @version $Revision: 1.0.0.1 $ $Date: 2006/08/30 13:59:59 $
  48. */
  49. public class DateUtil {
  50.  
  51. private static String defaultDatePattern = null;
  52.  
  53. private static String timePattern = "HH:mm";
  54.  
  55. /**
  56. * Return default datePattern (MM/dd/yyyy)
  57. *
  58. * @return a string representing the date pattern on the UI
  59. */
  60. public static synchronized String getDatePattern() {
  61. Locale locale = LocaleContextHolder.getLocale();
  62. try {
  63. /* extract default date pattern from application context */
  64. defaultDatePattern = ResourceBundle.getBundle("ApplicationResources", locale).getString("date.format");
  65. } catch (MissingResourceException mse) {
  66. defaultDatePattern = "MM/dd/yyyy";
  67. }
  68.  
  69. return defaultDatePattern;
  70. }
  71.  
  72. /**
  73. * Return default datetimePattern (MM/dd/yyyy HH:mm:ss.S)
  74. *
  75. * @return a string representing the datetime pattern on the UI
  76. */
  77. public static String getDateTimePattern() {
  78. return DateUtil.getDatePattern() + " HH:mm:ss.S";
  79. }
  80.  
  81. /**
  82. * This method attempts to convert an Oracle-formatted date in the form
  83. * dd-MMM-yyyy to mm/dd/yyyy.
  84. *
  85. * @param aDate
  86. * date from database as a string
  87. * @return formatted string for the ui
  88. */
  89. public static final String getDate(Date aDate) {
  90. SimpleDateFormat df = null;
  91. String returnValue = "";
  92. if (aDate != null) {
  93. df = new SimpleDateFormat(getDatePattern());
  94. returnValue = df.format(aDate);
  95. }
  96. return returnValue;
  97. }
  98.  
  99. /**
  100. * This method generates a string representation of a date/time in the
  101. * format you specify on input
  102. *
  103. * @param aMask
  104. * the date pattern the string is in
  105. * @param strDate
  106. * a string representation of a date
  107. * @return a converted Date object
  108. * @see java.text.SimpleDateFormat
  109. * @throws ParseException
  110. */
  111. public static final Date convertStringToDate(String aMask, String strDate) throws ParseException {
  112. SimpleDateFormat df = null;
  113. Date date = null;
  114. df = new SimpleDateFormat(aMask);
  115. try {
  116. date = df.parse(strDate);
  117. } catch (ParseException pe) {
  118. throw new ParseException(pe.getMessage(), pe.getErrorOffset());
  119. }
  120. return (date);
  121. }
  122.  
  123. public static Date convertXMLGregorianCalendar(XMLGregorianCalendar xmlcal) {
  124. GregorianCalendar grecal = xmlcal.toGregorianCalendar();
  125. return grecal.getTime();
  126. }
  127.  
  128. public static XMLGregorianCalendar getXMLGregorianCalendar() {
  129.  
  130. try {
  131. DatatypeFactory dtf = DatatypeFactory.newInstance();
  132. GregorianCalendar gcal = (GregorianCalendar) GregorianCalendar.getInstance();
  133. return dtf.newXMLGregorianCalendar(gcal);
  134. } catch (DatatypeConfigurationException e) {
  135. return null;
  136. }
  137. }
  138.  
  139. public static XMLGregorianCalendar getXMLGregorianCalendarDate(Date date) throws DatatypeConfigurationException {
  140. GregorianCalendar c = new GregorianCalendar();
  141. c.setTime(date);
  142. XMLGregorianCalendar xmlGdate = DatatypeFactory.newInstance().newXMLGregorianCalendar(c);
  143. return xmlGdate;
  144. }
  145.  
  146. public static long getTimeAlong(Date before, Date after) {
  147. return after.getTime() - before.getTime();
  148. }
  149.  
  150. /**
  151. * This method returns the current date time in the format: MM/dd/yyyy HH:MM
  152. * a
  153. *
  154. * @param theTime
  155. * the current time
  156. * @return the current date/time
  157. */
  158. public static String getTimeNow(Date theTime) {
  159. return getDateTime(timePattern, theTime);
  160. }
  161.  
  162. /**
  163. * This method returns the current date in the format: MM/dd/yyyy
  164. *
  165. * @return the current date
  166. * @throws ParseException
  167. */
  168. public static Calendar getToday() throws ParseException {
  169. Date today = new Date();
  170. SimpleDateFormat df = new SimpleDateFormat(getDatePattern());
  171.  
  172. String todayAsString = df.format(today);
  173. Calendar cal = new GregorianCalendar();
  174. cal.setTime(convertStringToDate(todayAsString));
  175.  
  176. return cal;
  177. }
  178.  
  179. /**
  180. * 最通用的时间方式
  181. *
  182. *
  183. * @param type
  184. * :样式,如:"yyyy-MM-dd HH:mm:ss.SSS"
  185. *
  186. */
  187. public static String getDateTime(String type) {
  188. Date aDate = DateUtil.currentSQLDate();
  189.  
  190. SimpleDateFormat df = null;
  191. String returnValue = "";
  192. if (aDate != null) {
  193. df = new SimpleDateFormat(type);
  194. returnValue = df.format(aDate);
  195. }
  196. return (returnValue);
  197.  
  198. }
  199.  
  200. /**
  201. * This method generates a string representation of a date's date/time in
  202. * the format you specify on input
  203. *
  204. * @param aMask
  205. * the date pattern the string is in
  206. * @param aDate
  207. * a date object
  208. * @return a formatted string representation of the date
  209. *
  210. * @see java.text.SimpleDateFormat
  211. */
  212. public static final String getDateTime(String aMask, Date aDate) {
  213. SimpleDateFormat df = null;
  214. String returnValue = "";
  215. if (aDate != null) {
  216. df = new SimpleDateFormat(aMask);
  217. returnValue = df.format(aDate);
  218. }
  219. return (returnValue);
  220. }
  221.  
  222. /**
  223. * This method generates a string representation of a date based on the
  224. * System Property 'dateFormat' in the format you specify on input
  225. *
  226. * @param aDate
  227. * A date to convert
  228. * @return a string representation of the date
  229. */
  230. public static final String convertDateToString(Date aDate) {
  231. return getDateTime(getDatePattern(), aDate);
  232. }
  233.  
  234. /**
  235. * This method converts a String to a date using the datePattern
  236. *
  237. * @param strDate
  238. * the date to convert (in format MM/dd/yyyy)
  239. * @return a date object
  240. *
  241. * @throws ParseException
  242. */
  243. public static Date convertStringToDate(String strDate) throws ParseException {
  244. Date aDate = null;
  245. try {
  246. aDate = convertStringToDate(getDatePattern(), strDate);
  247. } catch (ParseException pe) {
  248. pe.printStackTrace();
  249. throw new ParseException(pe.getMessage(), pe.getErrorOffset());
  250. }
  251. return aDate;
  252. }
  253.  
  254. public static java.sql.Timestamp currentSQLTimestamp() {
  255. return new java.sql.Timestamp(System.currentTimeMillis());
  256. }
  257.  
  258. public static synchronized java.sql.Date currentSQLDate() {
  259. return new java.sql.Date(System.currentTimeMillis());
  260. }
  261.  
  262. public static java.sql.Date getSQLDate(java.util.Date date) {
  263. return new java.sql.Date(date.getTime());
  264. }
  265.  
  266. public static java.sql.Timestamp getSQLTimestamp(java.util.Date date) {
  267. return new java.sql.Timestamp(date.getTime());
  268. }
  269.  
  270. public static java.util.Date toDate(String strValue) {
  271. SimpleDateFormat fmt = null;
  272. if (strValue.indexOf('.') > 0) {
  273. fmt = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS", Locale.CHINA);// 2005-01-01
  274. } else if (strValue.indexOf(':') > 0) {
  275. fmt = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.CHINA);// 2005-01-01
  276. // 10:10:10.100
  277. } else if (strValue.indexOf('-') > 0) {
  278. fmt = new SimpleDateFormat("yyyy-MM-dd", Locale.CHINA);// 2005-01-01
  279. }
  280. try {
  281. return fmt.parse(strValue);
  282. } catch (Exception ex) {
  283. return new Date();// 返回1970-01-01 00:00:00
  284. }
  285. }
  286.  
  287. public static java.sql.Timestamp toSQLTimestamp(String strValue) {
  288. return (new java.sql.Timestamp(toDate(strValue).getTime()));
  289. }
  290.  
  291. public static String getSQLDateTimeStr(java.util.Date date) {
  292. java.sql.Date sql_date = new java.sql.Date(date.getTime());
  293. java.sql.Time sql_time = new java.sql.Time(date.getTime());
  294. return sql_date + " " + sql_time;
  295. }
  296.  
  297. public static boolean comparableBefore(String strValue01, String strValue02) {
  298. return toSQLTimestamp(strValue01).before(toSQLTimestamp(strValue02));
  299. }
  300.  
  301. public static boolean comparableAfter(String strValue01, String strValue02) {
  302. return toSQLTimestamp(strValue01).after(toSQLTimestamp(strValue02));
  303. }
  304.  
  305. // 根据字符串返回该字符串对应的时间类型"00-00-00 00:00:00"
  306. public static String getbegintime(String begintime) {
  307. return getBegintime(begintime);
  308. }
  309. public static String getBegintime(String begintime) {
  310. if (begintime != null && begintime.length() == 8) {
  311. String yearString = begintime.substring(0, 4);
  312. String monthString = begintime.substring(4, 6);
  313. String dateString = begintime.substring(6);
  314. begintime = yearString + "-" + monthString + "-" + dateString + " " + "00:00:00";
  315. }
  316. return begintime;
  317. }
  318.  
  319. // 根据字符串返回该字符串对应的时间类型"00-00-00 24:00:00"
  320. public static String getEndtime(String endtime) {
  321. if (endtime != null && endtime.length() == 8) {
  322. String yearString = endtime.substring(0, 4);
  323. String monthString = endtime.substring(4, 6);
  324. String dateString = endtime.substring(6);
  325. endtime = yearString + "-" + monthString + "-" + dateString + " " + "24:00:00";
  326. }
  327. return endtime;
  328. }
  329.  
  330. // 根据字符串返回该字符串对应的日期类型"00-00-00"
  331. public static String getdate(String stringtime) {
  332. if (stringtime != null && stringtime.length() == 8) {
  333. String yearString = stringtime.substring(0, 4);
  334. String monthString = stringtime.substring(4, 6);
  335. String dateString = stringtime.substring(6);
  336. stringtime = yearString + "-" + monthString + "-" + dateString;
  337. }
  338. return stringtime;
  339. }
  340.  
  341. // 将2010-10-10类型转换成20101010格式
  342. public static String getString(String stringtime) {
  343. if (stringtime != null && stringtime.length() == 10) {
  344. String yearString = stringtime.substring(0, 4);
  345. String monthString = stringtime.substring(5, 7);
  346. String dateString = stringtime.substring(8);
  347. stringtime = yearString + monthString + dateString;
  348. }
  349. return stringtime;
  350. }
  351.  
  352. // 将日期转化为HH24MMSS格式的字符串
  353. public static String convertTohh24mmssFormat(Date date) {
  354. Calendar calendar = Calendar.getInstance();
  355. calendar.setTime(date);
  356. String hour = String.valueOf(calendar.get(Calendar.HOUR_OF_DAY));
  357. if (Integer.parseInt(hour) < 10) {
  358. hour = "0" + hour;
  359. }
  360. String minute = String.valueOf(calendar.get(Calendar.MINUTE));
  361. if (Integer.parseInt(minute) < 10) {
  362. minute = "0" + minute;
  363. }
  364. String second = String.valueOf(calendar.get(Calendar.SECOND));
  365. if (Integer.parseInt(second) < 10) {
  366. second = "0" + second;
  367. }
  368. String result = hour + minute + second;
  369. return result;
  370. }
  371.  
  372. // 获得两个日期的时间差,返回结果为_小时_分钟_秒
  373. public static String gettimedefferent(long milliseconds) {
  374. long hours = 0;
  375. long minutes = 0;
  376. long seconds = milliseconds / 1000;
  377. hours = seconds / 3600;
  378. seconds = seconds - hours * 3600;
  379. minutes = seconds / 60;
  380. seconds = seconds - minutes * 60;
  381. System.out.println(hours + "小时" + minutes + "分钟" + seconds + "秒");
  382. return hours + "小时" + minutes + "分钟" + seconds + "秒";
  383. }
  384.  
  385. /**
  386. * 获得几秒前的时间
  387. * @param date1 时间 yyyy-MM-dd HH:mm:ss
  388. * @param seconds 秒 1
  389. * @throws ParseException
  390. */
  391. public static String getTimeBefore(String date1, int seconds) throws ParseException{
  392. DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
  393. Date date = df.parse(date1);// 解析成日期格式
  394. date.setTime(date.getTime() - seconds * 1000);// 减去N秒的时间
  395.  
  396. return df.format(date);// 再将该时间转换成字符串格式
  397. }
  398.  
  399. /**
  400. * 得到几天后的时间 *
  401. *
  402. * @param d
  403. * @param day
  404. * @return
  405. */
  406. public static Date getDateAfter(Date d, int day) {
  407. Calendar now = Calendar.getInstance();
  408. now.setTime(d);
  409. now.set(Calendar.DATE, now.get(Calendar.DATE) + day);
  410. return now.getTime();
  411. }
  412.  
  413. /**
  414. * 标准日期时间比较大小
  415. * @param String
  416. * date1 "2014-3-14 18:47:08"
  417. * @param String
  418. * date2 "2014-3-14 18:47:09"
  419. * @return 毫秒数 1000(ms)
  420. */
  421. public static long diffDateTime(String date1, String date2) {
  422. DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
  423. long diff = 0;
  424. try {
  425. Date d1 = df.parse(date1);
  426. Date d2 = df.parse(date2);
  427. diff = d1.getTime() - d2.getTime();
  428. } catch (Exception e) {
  429. }
  430. return diff;
  431. }
  432.  
  433. public static String formatLongToTimeStr(Long l) {
  434. int hour = 0;
  435. int minute = 0;
  436. int second = 0;
  437. second = l.intValue() / 1000;
  438.  
  439. if (second > 60) {
  440. minute = second / 60;
  441. second = second % 60;
  442. }
  443. if (minute > 60) {
  444. hour = minute / 60;
  445. minute = minute % 60;
  446. }
  447. return (getTwoLength(hour) + getTwoLength(minute) + getTwoLength(second));
  448. }
  449.  
  450. public static String getTwoLength(final int data) {
  451. if (data < 10) {
  452. return "0" + data;
  453. } else {
  454. return "" + data;
  455. }
  456. }
  457.  
  458. /**
  459. * 将时长转换为分钟
  460. */
  461. public static String change2Minute(String duration) {
  462. if (duration.indexOf(":") >= 0) {
  463. String[] durationArr = duration.split(":");
  464. long hour = Long.parseLong(durationArr[0]);
  465. long minute = Long.parseLong(durationArr[1]);
  466. long second = Long.parseLong(durationArr[2]);
  467. if (second > 0) {
  468. duration = String.valueOf(hour * 60 + minute + 1);
  469. } else {
  470. duration = String.valueOf(hour * 60 + minute);
  471. }
  472. } else if (duration.matches("[0-9]+")) {
  473.  
  474. } else {
  475. System.out.println("格式不正确:" + duration);
  476. }
  477. return duration;
  478. }
  479.  
  480. /**
  481. * 获取当前标准日期时间
  482. */
  483. public static String getStandardNow() {
  484. return DateUtil.getDateTime("yyyy-MM-dd HH:mm:ss");
  485. }
  486.  
  487. /**
  488. * 获取运行时间
  489. * @param adddays为延期天数
  490. */
  491. public static String getStandardRound(String adddays) {
  492. return getStandardRound(adddays, true);
  493. }
  494.  
  495. /**
  496. * 获取运行时间 当前时间标准返回,未来时间只保留日期,时间为00:00:00
  497. * @param adddays 延期天数
  498. * @param readspecial 是否读取特殊含义值 keep 永不失效 将原值返回
  499. * @return
  500. */
  501. public static String getStandardRound(String adddays, boolean readspecial) {
  502. String runDate = new String();
  503. if ("".equals(adddays)) {
  504. adddays = "0";
  505. }
  506. if ("keep".equals(adddays)) {
  507. if (readspecial) {
  508. return "keep";
  509. } else {
  510. adddays = "0";
  511. }
  512. }
  513. if ("永不失效".equals(adddays)) {
  514. if (readspecial) {
  515. return "永不失效";
  516. } else {
  517. adddays = "0";
  518. }
  519. }
  520. /*
  521. * Pattern
  522. * pattern=Pattern.compile("\\d{4}-\\d{2}-\\d{2} \\d{2}:\\d{2}:\\d{2}");
  523. * Matcher matcher=pattern.matcher(runtime); if(matcher.find()){ runDate
  524. * = runtime; //已经是一个完成的时间格式yyyy-MM-dd HH:mm:ss }
  525. */
  526. if (adddays.indexOf(":") != -1) {
  527. runDate = adddays; // 已经是一个完成的时间格式yyyy-MM-dd HH:mm:ss
  528. } else {
  529. adddays = adddays.trim().replace("+", "").trim();
  530. runDate = DateUtil.getDateTime("yyyy-MM-dd HH:mm:ss");
  531. try {
  532. runDate = DateUtil.convertDateToString(DateUtil.getDateAfter(DateUtil.convertStringToDate(DateUtil.getDateTime("MM/dd/yyyy")),
  533. Integer.valueOf(adddays)));
  534. runDate = runDate.substring(6, 10) + "-" + runDate.substring(0, 2) + "-" + runDate.substring(3, 5) + " ";
  535. if (Integer.valueOf(adddays) == 0) {
  536. runDate += DateUtil.getDateTime("HH:mm:ss");
  537. } else {
  538. runDate += "00:00:00";
  539. }
  540. } catch (ParseException e) {
  541. e.printStackTrace();
  542. return runDate;
  543. }
  544. }
  545. return runDate;
  546. }
  547.  
  548. /**
  549. * 判断是否达到指定标准时间
  550. * @param date 2014-01-12 15:00:00
  551. * @return 达到true 未达到false
  552. */
  553. public static boolean isreachStandard(String date) {
  554. // 将仅含日期的date添加上时间
  555. if (date != null && date.length() == 10 && "-".equals(String.valueOf(date.charAt(4))) && "-".equals(String.valueOf(date.charAt(7)))) {
  556. date += " 00:00:00";
  557. }
  558. if (date == null || "null".equals(date) || date.length() != 19) {
  559. return false;
  560. }
  561. String nowdate = getStandardRound("0");
  562. if (nowdate.compareTo(date) < 0) {
  563. return false;
  564. } else {
  565. return true;
  566. }
  567. }
  568.  
  569. /**
  570. * 标准时长转为秒数
  571. * @param type : 26:15:04 -> 94504
  572. */
  573. public static long standardtime2secondslong(String duration) {
  574. long sum = 0;
  575. try {
  576. if (duration != null && duration.indexOf(":") >= 0) {
  577. String[] durationArr = duration.split(":");
  578. Long hour = Long.parseLong(durationArr[0]);
  579. Long minute = Long.parseLong(durationArr[1]);
  580. Long second = Long.parseLong(durationArr[2]);
  581. sum = hour * 3600 + minute * 60 + second;
  582. }
  583. } catch (Exception e) {
  584. e.printStackTrace();
  585. }
  586. return sum;
  587. }
  588.  
  589. /**
  590. * 秒数转为标准时长
  591. * @param type : 94504 -> 26:15:04
  592. *
  593. */
  594. public static String seconds2standardtime(Long seconds) {
  595. Long second = seconds % 60;
  596. Long minute = (seconds % 3600 - second) / 60;
  597. Long hour = (seconds - minute * 60 - second) / 3600;
  598. return hour + ":" + (minute >= 10 ? minute : "0" + minute) + ":" + (second >= 10 ? second : "0" + second);
  599. }
  600.  
  601. /**
  602. * 将yyyyMMdd格式的日期转换为标准格式
  603. * @param type : 20150105 -> 2015-01-05
  604. * @return
  605. */
  606. public static String yyyyMMdd2StandardDate(String stringdate) {
  607. if (stringdate != null && stringdate.length() == 8) {
  608. String yearString = stringdate.substring(0, 4);
  609. String monthString = stringdate.substring(4, 6);
  610. String dateString = stringdate.substring(6, 8);
  611. stringdate = yearString + "-" + monthString + "-" + dateString;
  612. }
  613. return stringdate;
  614. }
  615.  
  616. /**
  617. * 将获取的时间转换为标准时间
  618. * @param type : 135000 -> 13:50:00
  619. */
  620. public static String HHmmss2StandardTime(String HH24mmss) {
  621. if (HH24mmss != null && HH24mmss.length() == 6) {
  622. String hourString = HH24mmss.substring(0, 2);
  623. String minuteString = HH24mmss.substring(2, 4);
  624. String secondsString = HH24mmss.substring(4, 6);
  625. HH24mmss = hourString + ":" + minuteString + ":" + secondsString;
  626. }
  627. return HH24mmss;
  628. }
  629.  
  630. /**
  631. * 获取某标准日期时间节点经过某时长后的时间节点
  632. * 例初始时间节点: 2014-12-31 23:00:00
  633. * 经过时长:15:00:00
  634. * @return 2015-01-01 14:00:00
  635. */
  636. public static String StandardaddHHmmss(String starttime, String duration) {
  637. int durationtime = (int) DateUtil.standardtime2secondslong(duration);
  638. String endtime = starttime;
  639. // int starthour = Integer.parseInt(starttime.substring(11,12));
  640. // int startminute = Integer.parseInt(starttime.substring(14,15));
  641. //
  642. // int durationhour = Integer.parseInt(duration.substring(0,1));
  643. // int durationminute = Integer.parseInt(duration.substring(3,4));
  644.  
  645. // starttime = starttime.substring(11,18);
  646. // if(starttime)
  647. // String endtime = ;
  648. try {
  649. SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
  650. Date date = sdf.parse(starttime);
  651. Calendar calendar = Calendar.getInstance();
  652. calendar.setTime(date);
  653. calendar.add(Calendar.SECOND, durationtime);// 对秒数进行操作
  654.  
  655. endtime = sdf.format(calendar.getTime());
  656. } catch (ParseException e) {
  657. e.printStackTrace();
  658. }
  659.  
  660. return endtime;
  661. }
  662.  
  663. public static String formatDate(Date date,String formatter){
  664. try{
  665. SimpleDateFormat sdf = new SimpleDateFormat(formatter);
  666. return sdf.format(date);
  667. }catch(Throwable e){
  668. return "";
  669. }
  670. }
  671.  
  672. public static String formatDateWithT(Date date,String formatter){
  673. try{
  674. SimpleDateFormat sdf = new SimpleDateFormat(formatter);
  675. String temp = sdf.format(date);
  676. temp = temp.replace(" ", "T");
  677. return temp;
  678. }catch(Throwable e){
  679. return "";
  680. }
  681. }
  682.  
  683. public static Calendar formatString2Date(String date,String formateer){
  684. SimpleDateFormat format1 = new SimpleDateFormat(formateer);
  685. try {
  686. Date temp = format1.parse(date);
  687. Calendar cal = Calendar.getInstance();
  688. cal.setTime(temp);
  689. return cal;
  690. } catch (ParseException e) {
  691. return null;
  692. }
  693. }
  694.  
  695. public static Calendar formatString2DateWithT(String date,String formateer){
  696. date = date.replace("T", " ");
  697. SimpleDateFormat format1 = new SimpleDateFormat(formateer);
  698. try {
  699. Date temp = format1.parse(date);
  700. Calendar cal = Calendar.getInstance();
  701. cal.setTime(temp);
  702. return cal;
  703. } catch (ParseException e) {
  704. return null;
  705. }
  706. }
  707.  
  708. public static String getTransactionID(){
  709. Calendar cal = Calendar.getInstance();
  710. String transactionID = "" + cal.get(Calendar.YEAR) + cal.get(Calendar.MONTH) + cal.get(Calendar.DAY_OF_MONTH) + cal.get(Calendar.HOUR_OF_DAY) + cal.get(Calendar.MINUTE) + cal.get(Calendar.SECOND) ;
  711. return transactionID;
  712. }
  713.  
  714. // 计算间隔时间
  715. public String intervalTime(String beginTime, String endTime) throws ParseException{
  716. SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
  717. java.util.Date beginTimeDate = df.parse(beginTime);
  718. java.util.Date endTimeDate = df.parse(endTime);
  719.  
  720. long l = endTimeDate.getTime() - beginTimeDate.getTime();
  721. long day = l / (24 * 60 * 60 * 1000);
  722. long hour = (l / (60 * 60 * 1000) - day * 24);
  723. long min = ((l / (60 * 1000)) - day * 24 * 60 - hour * 60);
  724. long s = (l / 1000 - day * 24 * 60 * 60 - hour * 60 * 60 - min * 60);
  725.  
  726. return day + "天" + hour + "小时" + min + "分" + s + "秒";
  727. }
  728.  
  729. public static void main(String[] args) throws ParseException {
  730. // String startDate = "2014-09-22";
  731. // String startTime = "2014-09-22 09:05:02";
  732. // String endTime = "2014-09-22 12:00:00";
  733.  
  734. System.out.println(yyyyMMdd2StandardDate("20140102"));
  735. System.out.println(HHmmss2StandardTime("151617"));
  736. System.out.println(StandardaddHHmmss("2014-12-31 23:00:00","15:00:00"));
  737.  
  738. System.out.println("2015-04-24 11:00:00" + isreachStandard("2015-04-24 11:00:00"));
  739. System.out.println("2011-04-23" + isreachStandard("2011-04-23"));
  740. System.out.println("EMPTY" + isreachStandard(""));
  741. System.out.println("123" + isreachStandard("123"));
  742. System.out.println(isreachStandard(null));
  743. //
  744. // Calendar cal = Calendar.getInstance();
  745. // String s = formatDate(cal.getTime(),"yyyy-MM-ddThh:mm:ss");
  746. // String s1 = formatDateWithT(cal.getTime(),"yyyy-MM-dd HH:mm:ss");
  747. //
  748. // System.out.println(s + "\n" + s1 + "\n" + new Timestamp(cal.getTime().getTime()));
  749. System.out.println("2011-04-23".length());
  750.  
  751. // 计算间隔时间
  752. DateUtil dateUtil = new DateUtil();
  753. String beginTime = "2009-02-28 11:30:41";
  754. String endTime = "2009-03-01 13:31:40";
  755. String str = dateUtil.intervalTime(beginTime,endTime);
  756. System.out.println(str);
  757.  
  758. }
  759. }

Java中的操作日期的工具类的更多相关文章

  1. java里poi操作excel的工具类(兼容各版本)

    转: java里poi操作excel的工具类(兼容各版本) 下面是文件内具体内容,文件下载: import java.io.FileNotFoundException; import java.io. ...

  2. Java中的AES加解密工具类:AESUtils

    本人手写已测试,大家可以参考使用 package com.mirana.frame.utils.encrypt; import com.mirana.frame.constants.SysConsta ...

  3. java中使用反射做一个工具类,来为指定类中的成员变量进行赋值操作,使用与多个类对象的成员变量的赋值。

    //------------------------------------------------我是代码的分割线 // 首选是一个工具类,在该工具类里面,定义了一个方法,public void s ...

  4. java中redis的分布式锁工具类

    使用方式 try { if(PublicLock.getLock(lockKey)){ //这里写代码逻辑,执行完后需要释放锁 PublicLock.freeLock(lockKey); } } ca ...

  5. Java中的4个并发工具类 CountDownLatch CyclicBarrier Semaphore Exchanger

    在 java.util.concurrent 包中提供了 4 个有用的并发工具类 CountDownLatch 允许一个或多个线程等待其他线程完成操作,课题点 Thread 类的 join() 方法 ...

  6. java中的数组的Arrays工具类的使用

    package day04.d1.shuzu; import java.util.Arrays; /** * Arrays 工具类 * @author Administrator * */public ...

  7. java中常用的16个工具类

    1. org.apache.commons.io.IOUtils:处理io流的相关操作 closeQuietly ( ) toString ( ) copy ( ) toByteArray ( ) w ...

  8. java中Arrays和Collections等工具类

    java.util.Arrays类能方便地操作数组,它提供的所有方法都是静态的.具有以下功能: ² 给数组赋值:通过fill方法. ² 对数组排序:通过sort方法,按升序. ² 比较数组:通过equ ...

  9. Java中的RSA加解密工具类:RSAUtils

    本人手写已测试,大家可以参考使用 package com.mirana.frame.utils.encrypt; import com.mirana.frame.utils.log.LogUtils; ...

随机推荐

  1. 建表的sql

    1. 创建用户表 create table user( id int unsigned not null primary key auto_increment comment '自增id', user ...

  2. Cipher Message

    http://acm.hust.edu.cn/vjudge/contest/view.action?cid=34121#problem/C // File Name: c.cpp // Author: ...

  3. Castle IOC容器组件生命周期管理

    主要内容 1.生命处理方式 2.自定义生命处理方式 3.生命周期处理 一.生命处理方式 我们通常创建一个组件的实例使用new关键字,这样每次创建出来的都是一个新的实例,如果想要组件只有一个实例,我们会 ...

  4. wbadmin与vssadmin

    wbadmin作为应用程序,在备份的时候调用vssadmin进行卷影副本备份. 创建分区还原点也是利用了vssadmin. 试验: 1.通过wsb对一个文件夹进行备份,备份完成后在wsb中会有一个副本 ...

  5. 关于 TIdHttp

    经验总结: 1.IdHttp 不支持多线程,只支持异步.所有网上的多线程写法下,如果同时并发多个长 GET 或 POST 请求时,会阻塞. 以下代码用于显示下载数据的进程. procedure TFo ...

  6. 用java发送邮件(黄海已测试通过)

    /** * java发送带附件的邮件 * 周枫 * 2013.8.10 */ package com.dsideal.Util; import javax.mail.*; import javax.m ...

  7. web及移动应用测试知识总结

    发现自己对测试知识的掌握不够系统,在这里整理一下好了. 1. 通用测试点 功能测试 正向:输入一个有效的输入并且期望软件能够完成一些根据说明书规定的行为 逆向:输入一个无效的输入并且期望软件给出合理的 ...

  8. hdu 5265 pog loves szh II STL

    pog loves szh II Time Limit: 20 Sec Memory Limit: 256 MB 题目连接 http://acm.hdu.edu.cn/showproblem.php? ...

  9. C# API: 生成和读取Excel文件

    我们想为用户提供一些数据,考虑再三, 大家认为对于用户(人,而非机器)的可读性, Excel文件要好一些. 因为相比csv,xml等文件, Excel中我们可以运用自动筛选, 窗口锁定, 还可以控制背 ...

  10. 50个Android开发人员必备UI效果源码[转载]

    50个Android开发人员必备UI效果源码[转载] http://blog.csdn.net/qq1059458376/article/details/8145497 Android 仿微信之主页面 ...