DateUtil.java 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. package cn.com.qmth.importpaper;
  2. import java.text.ParseException;
  3. import java.text.SimpleDateFormat;
  4. import java.util.Date;
  5. /**
  6. * 日期工具
  7. *
  8. * @author WANGWEI
  9. */
  10. public class DateUtil {
  11. /**
  12. * patterns describing the date and time format
  13. *
  14. * @author WANGWEI
  15. */
  16. public interface DatePatterns {
  17. public static final String DEFAULT = "yyyyMMddHHmmss";
  18. public static final String YYYY = "yyyy";
  19. public static final String YYYYMM = "yyyyMM";
  20. public static final String YYYYMMDD = "yyyyMMdd";
  21. public static final String YYYYMMDDHH = "yyyyMMddHH";
  22. public static final String YYYYMMDDHHMM = "yyyyMMddHHmm";
  23. public static final String ISO = "yyyy-MM-dd HH:mm:ss";
  24. public static final String YYYY_MM = "yyyy-MM";
  25. public static final String YYYY_MM_DD = "yyyy-MM-dd";
  26. public static final String YYYY_MM_DD_HH_MM = "yyyy-MM-dd HH:mm";
  27. public static final String YYYY_MM_DD_HH_MM_SS_SSS = "yyyy-MM-dd HH:mm:ss.SSS";
  28. }
  29. /**
  30. * get now date.
  31. *
  32. * @param pattern
  33. * @return
  34. */
  35. public static String getNow(String pattern) {
  36. return format(new Date(), pattern);
  37. }
  38. /**
  39. * get now ISO date.
  40. *
  41. * @return
  42. */
  43. public static String getNowISO() {
  44. return format(new Date(), DatePatterns.ISO);
  45. }
  46. /**
  47. * format date.
  48. *
  49. * @param date
  50. * @param pattern
  51. * @return
  52. */
  53. public static String format(Date date, String pattern) {
  54. try {
  55. SimpleDateFormat df = new SimpleDateFormat(pattern);
  56. return df.format(date);
  57. } catch (Exception e) {
  58. throw new RuntimeException(e);
  59. }
  60. }
  61. /**
  62. * parse date.
  63. *
  64. * @param source
  65. * @param pattern
  66. * @return
  67. */
  68. public static Date parse(String source, String pattern) {
  69. SimpleDateFormat df = new SimpleDateFormat(pattern);
  70. try {
  71. return df.parse(source);
  72. } catch (ParseException e) {
  73. throw new RuntimeException(e);
  74. }
  75. }
  76. }