在項目中,很多地方需要根據時間獲取相應的數據,將時間格式化,或者時間比較等相關操作。一個良好的工具類不僅可以減少代碼冗餘,還能促進業務處理,加快進度。 輸出結果: ...
在項目中,很多地方需要根據時間獲取相應的數據,將時間格式化,或者時間比較等相關操作。一個良好的工具類不僅可以減少代碼冗餘,還能促進業務處理,加快進度。
/** * @author: lxw * @Date: 2018/12/25 14:36 * @Description: 時間工具類 */ public class DateUtils { /** * 常用時間格式 */ public final static String DATE_TIME_PATTERN = "yyyy-MM-dd HH:mm:ss"; public final static String MONTH_PATTERN = "yyyy-MM"; public final static String DATE_PATTERN = "yyyy-MM-dd"; public final static String HH_MM_SS = "HH:mm:ss"; public final static String DATE_PATTERN_YYYY_MM_DD_HH_MM = "yyyy-MM-dd HH:mm"; public static String DATE_TIME_PATTERN_YYYY_MM_DD_HH_MM_SS_SSS = "yyyyMMddHHmmssSSS"; public static String DATE_TIME_PATTERN_YYYY_MM_DD_HH_MM_SS = "yyyyMMddHHmmss"; /** * 日期轉換格式數組 */ public static String[][] regularExp = new String[][]{ // 預設格式 {"\\d{4}-((([0][1,3-9]|[1][0-2]|[1-9])-([0-2]\\d|[3][0,1]|[1-9]))|((02|2)-(([1-9])|[0-2]\\d)))\\s+([0,1]\\d|[2][0-3]|\\d):([0-5]\\d|\\d):([0-5]\\d|\\d)", DATE_TIME_PATTERN}, // 僅日期格式 年月日 {"\\d{4}-((([0][1,3-9]|[1][0-2]|[1-9])-([0-2]\\d|[3][0,1]|[1-9]))|((02|2)-(([1-9])|[0-2]\\d)))", DATE_PATTERN}, // 帶毫秒格式 {"\\d{4}((([0][1,3-9]|[1][0-2]|[1-9])([0-2]\\d|[3][0,1]|[1-9]))|((02|2)(([1-9])|[0-2]\\d)))([0,1]\\d|[2][0-3])([0-5]\\d|\\d)([0-5]\\d|\\d)\\d{1,3}", DATE_TIME_PATTERN_YYYY_MM_DD_HH_MM_SS_SSS} }; /** * 日期轉換為String類型 * * @param date 日期 * @param pattern 獲取格式 * @return String */ public static String format(Date date, String pattern) { if (date != null) { SimpleDateFormat df = new SimpleDateFormat(pattern); return df.format(date); } return null; } /** * 日期轉換為String類型,並添加或減少相應的天數 * * @param date 日期 * @param pattern 獲取格式 * @param amount 天數 * @return String */ public static String format(Date date, String pattern, int amount) { if (date != null) { Calendar calendar = Calendar.getInstance(); calendar.setTime(date); calendar.add(Calendar.DAY_OF_MONTH, amount); SimpleDateFormat df = new SimpleDateFormat(pattern); return df.format(calendar.getTime()); } return null; } /** * 字元串轉換成日期 * * @param strDate 日期字元串 * @param pattern 日期的格式 * @return data */ public static Date stringToDate(String strDate, String pattern) { if (StringUtils.isBlank(strDate)) { return null; } DateTimeFormatter fmt = DateTimeFormat.forPattern(pattern); return fmt.parseLocalDateTime(strDate).toDate(); } /** * 兩個時間之間的天數 * * @param date1 * @param date2 * @param pattern 格式 * @return 天數 */ public static long getDays(String date1, String date2, String pattern) { SimpleDateFormat formatter = new SimpleDateFormat(pattern); if (date1 == null || date1.equals("")) { return 0; } if (date2 == null || date2.equals("")) { return 0; } try { Date date = formatter.parse(date1); Date newDate = formatter.parse(date2); return (date.getTime() - newDate.getTime()) / (24 * 60 * 60 * 1000); } catch (Exception e) { } return 0; } /** * 產生周序列,即得到當前時間所在的年度是第幾周 * * @return */ public static String getSeqWeek() { Calendar c = Calendar.getInstance(Locale.CHINA); String week = Integer.toString(c.get(Calendar.WEEK_OF_YEAR)); if (week.length() == 1) { week = "0" + week; } return week; } /** * 日期格式字元串轉換成時間戳 * * @param date_str 字元串日期 * @param format 日期格式,如:yyyy-MM-dd HH:mm:ss * @return */ public static String dateTimeStamp(String date_str, String format) { try { SimpleDateFormat sdf = new SimpleDateFormat(format); return String.valueOf(sdf.parse(date_str).getTime() / 1000); } catch (Exception e) { e.printStackTrace(); } return ""; } /** * 獲取日期的格式 * * @param date_str 日期格式字元串 * @return 當前日期格式 */ public static String getDateFormat(String date_str) { String style = null; if (org.springframework.util.StringUtils.isEmpty(date_str)) { return null; } boolean b = false; for (int i = 0; i < regularExp.length; i++) { b = date_str.matches(regularExp[i][0]); if (b) { style = regularExp[i][1]; } } if (org.springframework.util.StringUtils.isEmpty(style)) { return null; } return style; } /** * 轉換為時間類型格式 * * @param strDate 日期 * @return */ public static Date strToDate(String strDate) { try { String strType = getDateFormat(strDate); if (strType == null) { return null; } SimpleDateFormat sf = new SimpleDateFormat(strType); return new Date((sf.parse(strDate).getTime())); } catch (Exception e) { return null; } } /** * 獲取兩個字元串時間差 * * @param beginTime 開始時間 * @param endTime 結束時間 * @return xx小時xx分鐘 */ public static String timeLength(String beginTime, String endTime) { if (beginTime == null || "".equals(beginTime)) { return ""; } if (endTime == null || "".equals(endTime)) { return ""; } Date begin = DateUtils.strToDate(beginTime); Date end = DateUtils.strToDate(endTime); if (begin == null || end == null) { return ""; } try { //除以1000是為了轉換成秒 long between = (end.getTime() - begin.getTime()) / 1000; int day = (int) between / (24 * 3600); int hour = (int) between % (24 * 3600) / 3600; int minute = (int) between % 3600 / 60; int currentHour = day * 24 + hour; return currentHour + "小時" + minute + "分鐘"; } catch (Exception e) { return ""; } } /** * 判斷是否潤年 * * @param date 日期 * @return boolean */ public static boolean isLeapYear(Date date) { /** * 1.被400整除是閏年 * 2.不能被4整除則不是閏年 * 3.能被4整除同時不能被100整除則是閏年 * 4.能被4整除同時能被100整除則不是閏年 */ GregorianCalendar gc = (GregorianCalendar) Calendar.getInstance(); gc.setTime(date); int year = gc.get(Calendar.YEAR); if ((year % 400) == 0) { return true; } else if ((year % 4) == 0) { if ((year % 100) == 0) { return false; } else { return true; } } else { return false; } } /** * 取得當前時間生成格式為yyyymmddhhmmss+k位隨機數 * * @param k 隨機數位數 */ public static String getNo(int k) { Date date = new Date(); return format(date, DATE_TIME_PATTERN_YYYY_MM_DD_HH_MM_SS) + getRandom(k); } /** * 返回一個隨機數 * * @param num 隨機生成的位數 * @return */ public static String getRandom(int num) { Random random = new Random(); if (num == 0) { return ""; } String randomNum = ""; for (int i = 0; i < num; i++) { //取0-9的隨機數進行拼接 randomNum += random.nextInt(9); } return randomNum; } /** * 根據周數,獲取開始日期、結束日期 * * @param week 周期 0本周,-1上周,-2上上周,1下周,2下下周 * @return 返回date[0]開始日期、date[1]結束日期 */ public static Date[] getWeekStartAndEnd(int week) { DateTime dateTime = new DateTime(); LocalDate date = new LocalDate(dateTime.plusWeeks(week)); date = date.dayOfWeek().withMinimumValue(); Date beginDate = date.toDate(); Date endDate = date.plusDays(6).toDate(); return new Date[]{beginDate, endDate}; } /** * 對日期的【秒】進行加/減 * * @param date 日期 * @param seconds 秒數,負數為減 * @return 加/減幾秒後的日期 */ public static Date addDateSeconds(Date date, int seconds) { DateTime dateTime = new DateTime(date); return dateTime.plusSeconds(seconds).toDate(); } /** * 對日期的【分鐘】進行加/減 * * @param date 日期 * @param minutes 分鐘數,負數為減 * @return 加/減幾分鐘後的日期 */ public static Date addDateMinutes(Date date, int minutes) { DateTime dateTime = new DateTime(date); return dateTime.plusMinutes(minutes).toDate(); } /** * 對日期的【小時】進行加/減 * * @param date 日期 * @param hours 小時數,負數為減 * @return 加/減幾小時後的日期 */ public static Date addDateHours(Date date, int hours) { DateTime dateTime = new DateTime(date); return dateTime.plusHours(hours).toDate(); } /** * 對日期的【天】進行加/減 * * @param date 日期 * @param days 天數,負數為減 * @return 加/減幾天後的日期 */ public static Date addDateDays(Date date, int days) { DateTime dateTime = new DateTime(date); return dateTime.plusDays(days).toDate(); } /** * 對日期的【周】進行加/減 * * @param date 日期 * @param weeks 周數,負數為減 * @return 加/減幾周後的日期 */ public static Date addDateWeeks(Date date, int weeks) { DateTime dateTime = new DateTime(date); return dateTime.plusWeeks(weeks).toDate(); } /** * 對日期的【月】進行加/減 * * @param date 日期 * @param months 月數,負數為減 * @return 加/減幾月後的日期 */ public static Date addDateMonths(Date date, int months) { DateTime dateTime = new DateTime(date); return dateTime.plusMonths(months).toDate(); } /** * 對日期的【年】進行加/減 * * @param date 日期 * @param years 年數,負數為減 * @return 加/減幾年後的日期 */ public static Date addDateYears(Date date, int years) { DateTime dateTime = new DateTime(date); return dateTime.plusYears(years).toDate(); } /** * 比較時間大小 * * @param exprtime 時間1 * @param times 時間2 * @return 0:時間相等 1;時間1在時間2之後 -1:時間1在時間2之前 */ public static int compareDate(String exprtime, String times) { int result = 0; //判斷時間大小 if (exprtime != null && !"".equals(exprtime)) { DateFormat dateFormat = new SimpleDateFormat(DATE_TIME_PATTERN); try { Date d1 = dateFormat.parse(exprtime); Date d2 = dateFormat.parse(times); if (d1.getTime() > d2.getTime()) { System.out.println(d1 + "在" + d2 + "之後"); result = 1; } else if (d1.getTime() < d2.getTime()) { result = -1; System.out.println(d1 + "在" + d2 + "之前"); } else { System.out.println(d1 + "=" + d2); } } catch (ParseException e) { e.printStackTrace(); System.out.println("方法——compareDate異常"); } } return result; } /** * 獲取距離現在的天數 * * @param exprtime 某天的時間字元串 * @return 天數 */ public static long getDays(String exprtime) { Date begin = DateUtils.strToDate(format(new Date(), DATE_TIME_PATTERN)); Date end = DateUtils.strToDate(exprtime); long between = (end.getTime() - begin.getTime()) / 1000; int day = (int) between / (24 * 3600); return day; } ``` 測試類方法: ``` public static void main(String[] args) { Date date = new Date(); String dateString = DateUtils.format(date, DATE_TIME_PATTERN); System.out.println("時間格式轉換為:" + dateString); String tomorrow = DateUtils.format(date, DATE_TIME_PATTERN, 1); System.out.println("明天日期:" + tomorrow); Date stringToDate = DateUtils.stringToDate(dateString, DATE_TIME_PATTERN); System.out.println("當天日期格式:" + stringToDate); boolean flag = DateUtils.isLeapYear(date); System.out.println("當前是否為閏年:" + flag); long days = DateUtils.getDays(tomorrow, dateString, DATE_PATTERN); System.out.println("天數相差:" + days + " 天"); String getSeqWeek = DateUtils.getSeqWeek(); System.out.println("今年第 " + getSeqWeek + " 周"); String randomNum = DateUtils.getNo(4); System.out.println("編號:" + randomNum); String dateTimeStamp = DateUtils.dateTimeStamp(dateString, DATE_TIME_PATTERN); System.out.println("當期時間戳:" + dateTimeStamp); String timeLength = DateUtils.timeLength(dateString, tomorrow); System.out.println("相差時間:" + timeLength); String getDateFormat = DateUtils.getDateFormat(dateString); System.out.println("當前日期格式:" + getDateFormat); String stmpString = DateUtils.stampToDate("1545732716"); System.out.println("當前日期:" + stmpString); String stmpLong = DateUtils.stampToDate(1545732716L); System.out.println("當前日期:" + stmpLong); long day = DateUtils.getDays("2019-01-01 18:20:20"); System.out.println("距離當前時間:" + day + "天"); }
輸出結果:
時間格式轉換為:2018-12-25 18:21:23 明天日期:2018-12-26 18:21:23 當天日期格式:Tue Dec 25 18:21:23 CST 2018 當前是否為閏年:false 天數相差:1 天 今年第 52 周 編號:201812251821237084 當期時間戳:1545733283 相差時間:24小時0分鐘 當前日期格式:yyyy-MM-dd HH:mm:ss 當前日期:1970-01-19 05:22:12 當前日期:1970-01-19 05:22:12 距離當前時間:6天