今天分享一個日期獲取和計算的工具類,這個最初是用在項目中獲取每週每個月日期用的。java
<Attention> 以後逛帖子的時候發現了這個專門處理日期的庫,java上也有,android上還爲了不使用getResourceAsStream
而拖慢app這個問題進行了優化,地址爲android
package com.ran.interview; import java.text.DateFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; import java.util.Locale; /** * @author BMR * @ClassName: CalendarHelper * @Description: 日期計算工具,標準格式yyyy-MM-dd下各類日期的獲取和計算 * @date 2016/2/26 16:08 */ public class CalendarHelper { private static SimpleDateFormat yyyyMMddFormat; public final static String[] mMonthCN = new String[]{"一月", "二月", "三月", "四月", "五月", "六月", "七月", "八月", "九月", "十月", "十一月", "十二月"}; public static void setup() { yyyyMMddFormat = new SimpleDateFormat("yyyy-MM-dd", Locale.ENGLISH); } /** * 顯示格式化的月日:eg,2013-03-27,convert to 03月27日 * * @param dateStr eg,2013-03-27 * @return 03月27日 */ public static String formatToDay(String dateStr) { if (CalendarHelper.isStrEmpty(dateStr)) { return ""; } //DateFormat localFormat = DateFormat.getDateInstance(DateFormat.MEDIUM, Locale.CHINA);
//在android中上面的Medium也能夠獲得中文結果,可是直接用java運行的時候不能夠,只能改用這個LONG型的了
DateFormat localFormat = DateFormat.getDateInstance(DateFormat.LONG, Locale.CHINESE); Date date; String formatDate = null; try { date = getDateFromString(dateStr, null); formatDate = localFormat.format(date); formatDate = formatDate.substring(5); } catch (ParseException e) { e.printStackTrace(); } return formatDate; } /** * 顯示格式化的月,中文的月份 * * @param dateStr eg,2013-03-27 * @return 三月 */ public static String formatToMonth(String dateStr) { if (CalendarHelper.isStrEmpty(dateStr)) { return ""; } if(dateStr.length() < 7){ return ""; } String month = dateStr.substring(5, 7); int index = Integer.parseInt(month); String formatDate = ""; if (index > 0 && index < 13) { formatDate = mMonthCN[index - 1]; } return formatDate; } /** * 檢查字符串是不是今天 * * @param dateStr */ public static boolean checkIsToday(String dateStr) { Calendar calendar = Calendar.getInstance(); Date currentDate = calendar.getTime(); return getStringFromDate(currentDate, null).equals(dateStr); } /** * Get the Date from String with custom format. Default format is yyyy-MM-dd * * @param dateString * @param dateFormat * @return * @throws ParseException */ public static Date getDateFromString(String dateString, String dateFormat) throws ParseException { SimpleDateFormat formatter; if (dateFormat == null) { if (yyyyMMddFormat == null) { setup(); } formatter = yyyyMMddFormat; } else { formatter = new SimpleDateFormat(dateFormat, Locale.ENGLISH); } return formatter.parse(dateString); } /** * Convert the Date to String with custom format. Default format is yyyy-MM-dd * * @param date * @param dateFormat * @return */ public static String getStringFromDate(Date date, String dateFormat) { String dateString = null; SimpleDateFormat formatter; if (date == null) { return null; } if (dateFormat == null) { if (yyyyMMddFormat == null) { setup(); } formatter = yyyyMMddFormat; } else { formatter = new SimpleDateFormat(dateFormat, Locale.ENGLISH); } dateString = formatter.format(date); return dateString; } /** * 獲取當天的日期 * * @return */ public static String getTodayDateString() { SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd", Locale.ENGLISH); return dateFormat.format(new Date()); } /** * 獲取指定日期的偏移後的日期字符串,offset>0日期向後,<0向前 * * @param dateStr * @param offset * @return */ public static String getDateStringByOffset(String dateStr, int offset) { if (offset == 0) { return dateStr; } Date date; String newDateStr = null; try { date = getDateFromString(dateStr, null); Calendar cal = Calendar.getInstance(); cal.setTime(date); cal.add(Calendar.DATE, offset); newDateStr = getStringFromDate(cal.getTime(), null); } catch (ParseException e) { e.printStackTrace(); } return newDateStr; } /** * 獲取輸入日期所在周的開始日期 (週一),默認格式 yyyy-MM-dd * * @param date * @return String */ public static String getFirstDayOfWeek(Date date, String dateFormat) { String firstDay; if (date == null) { return null; } Calendar calendar = Calendar.getInstance(); calendar.setTime(date); if (calendar.get(Calendar.DAY_OF_WEEK) == 1) { calendar.add(Calendar.DATE, -7); } calendar.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY); Date newDate = calendar.getTime(); firstDay = getStringFromDate(newDate, dateFormat); return firstDay; } /** * 獲取輸入日期所在周的結束日期 (週日),默認格式 yyyy-MM-dd * * @param date * @return String */ public static String getLastDayOfWeek(Date date, String dateFormat) { String lastDay; if (date == null) { return null; } Calendar calendar = Calendar.getInstance(); calendar.setTime(date); // 默認週日是本週的開始, if (calendar.get(Calendar.DAY_OF_WEEK) != 1) { // 非週末的狀況要先加一週才能得到本週的週末 calendar.add(Calendar.DATE, 7); } calendar.set(Calendar.DAY_OF_WEEK, Calendar.SUNDAY); Date newDate = calendar.getTime(); lastDay = getStringFromDate(newDate, dateFormat); return lastDay; } /** * 得到指定日期與指定週數間隔的那週週一的日期 * * @param date 正數是count週數以後,負數時count週數以前,0 返回本週週一日期 * @param dateFormat * @return */ public static String getFirstDayOfPreviousWeek(Date date, int count, String dateFormat) { String firstDay; if (date == null) { return null; } if (count == 0) { return getFirstDayOfWeek(date, dateFormat); } Calendar calendar = Calendar.getInstance(); calendar.setTime(date); // 默認週日是本週的開始,若是是週末,不加 if (calendar.get(Calendar.DAY_OF_WEEK) == 1) { calendar.add(Calendar.DATE, (count - 1) * 7); } else { calendar.add(Calendar.DATE, count * 7); } calendar.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY); Date newDate = calendar.getTime(); firstDay = getStringFromDate(newDate, dateFormat); return firstDay; } /** * 得到指定日期與指定週數間隔的那週週日的日期 * * @param date 正數是count週數以後,負數時count週數以前,0 返回本週週日日期 * @param dateFormat * @return */ public static String getLastDayOfPreviousWeek(Date date, int count, String dateFormat) { String lastDay; if (date == null) { return null; } if (count == 0) { return getLastDayOfWeek(date, dateFormat); } Calendar calendar = Calendar.getInstance(); calendar.setTime(date); // 默認週日是本週的開始,要先加一週才能得到本週的週末。若是是週末,不加 if (calendar.get(Calendar.DAY_OF_WEEK) == 1) { calendar.add(Calendar.DATE, (count) * 7); } else { // 非週末的狀況要先加一週才能得到本週的週末 calendar.add(Calendar.DATE, (count + 1) * 7); } calendar.set(Calendar.DAY_OF_WEEK, Calendar.SUNDAY); Date newDate = calendar.getTime(); lastDay = getStringFromDate(newDate, dateFormat); return lastDay; } /** * 獲取輸入日期所在月的開始日期,默認格式 yyyy-MM-dd * * @param date * @return */ public static String getFirstDayOfMonth(Date date, String dateFormat) { String firstDay; if (date == null) { return null; } Calendar calendar = Calendar.getInstance(); calendar.setTime(date); calendar.set(Calendar.DATE, 1); Date newDate = calendar.getTime(); firstDay = getStringFromDate(newDate, dateFormat); return firstDay; } /** * 獲取輸入日期所在月的結束日期,默認格式 yyyy-MM-dd * * @param date * @return String */ public static String getLastDayOfMonth(Date date, String dateFormat) { String lastDay; if (date == null) { return null; } Calendar calendar = Calendar.getInstance(); calendar.setTime(date); calendar.set(Calendar.DAY_OF_MONTH, calendar.getActualMaximum(Calendar.DAY_OF_MONTH)); Date newDate = calendar.getTime(); lastDay = getStringFromDate(newDate, dateFormat); return lastDay; } /** * 獲取輸入日期和間隔月份所在月的開始日期,默認格式 yyyy-MM-dd * * @param date * @param count * @return */ public static String getFirstDayOfPreviousMonth(Date date, int count, String dateFormat) { String firstDay; if (date == null) { return null; } if (count == 0) { return getFirstDayOfMonth(date, dateFormat); } Calendar calendar = Calendar.getInstance(); calendar.setTime(date); calendar.add(Calendar.MONTH, count); calendar.set(Calendar.DATE, 1); Date newDate = calendar.getTime(); firstDay = getStringFromDate(newDate, dateFormat); return firstDay; } /** * 獲取輸入日期和間隔月份所在月的最後日期,默認格式 yyyy-MM-dd * * @param date * @param count * @return */ public static String getLastDayOfPreviousMonth(Date date, int count, String dateFormat) { String firstDay; if (date == null) { return null; } if (count == 0) { return getLastDayOfMonth(date, dateFormat); } Calendar calendar = Calendar.getInstance(); calendar.setTime(date); calendar.add(Calendar.MONTH, count); calendar.set(Calendar.DATE, calendar.getActualMaximum(Calendar.DAY_OF_MONTH)); Date newDate = calendar.getTime(); firstDay = getStringFromDate(newDate, dateFormat); return firstDay; } /** * 計算兩個日期字符串之間的天數,格式2011-12-26 * * @param dateStart 起始日期 * @param dateEnd 結束日期 * @return */ public static int getIntervalDay(String dateStart, String dateEnd) { Date dateFrom; Date dateTo; long gap = 0; try { dateFrom = getDateFromString(dateStart, null); dateTo = getDateFromString(dateEnd, null); Calendar cal = Calendar.getInstance(); cal.setTime(dateFrom); long timeFrom = cal.getTimeInMillis(); cal.setTime(dateTo); long timeTo = cal.getTimeInMillis(); gap = (timeTo - timeFrom) / (1000 * 3600 * 24); gap = gap + 1; //從間隔毫秒變成間隔天數</strong> } catch (ParseException e) { e.printStackTrace(); } return (int)gap; } /** * 判斷字符串是否爲空 * * @param str * @return */ public static boolean isStrEmpty(String str) { if (null == str || "".equals(str.trim()) || "null".equals(str)) { return true; } return false; } }
最後附上幾個簡單的測試用例:git
package com.ran.interview; import java.util.Date; /** * @ClassName: CalendarHelperTest * @Description: TODO * @author BMR * @date 2016年3月15日 上午11:00:49 */ public class CalendarHelperTest { public static void main(String[] args){ String todayStr = CalendarHelper.getTodayDateString(); System.out.println("today is: "+ todayStr); System.out.println("check is today: "+ CalendarHelper.checkIsToday(todayStr)); System.out.println("today is (Chinese format): "+ CalendarHelper.formatToDay(todayStr)); System.out.println("今天所在周的週一: "+ CalendarHelper.getFirstDayOfWeek(new Date(), null)); System.out.println("今天所在周的週末: "+ CalendarHelper.getLastDayOfWeek(new Date(), null)); System.out.println("指定日期的格式化的月,中文的月份: "+ CalendarHelper.formatToMonth(todayStr)); System.out.println("獲取輸入日期所在月的開始日期: "+ CalendarHelper.getFirstDayOfMonth(new Date(), null)); System.out.println("獲取輸入日期所在月的結束日期: "+ CalendarHelper.getLastDayOfMonth(new Date(), null)); System.out.println("得到指定日期與指定週數間隔的那週週一的日期: "+ CalendarHelper.getFirstDayOfPreviousWeek(new Date(), 2, null)); System.out.println("得到指定日期與指定週數間隔的那週週末的日期: "+ CalendarHelper.getLastDayOfPreviousWeek(new Date(), -2, null)); System.out.println("獲取輸入日期和間隔月份所在月的開始日期: "+ CalendarHelper.getFirstDayOfPreviousMonth(new Date(), 2, null)); System.out.println("獲取輸入日期和間隔月份所在月的最後日期: "+ CalendarHelper.getLastDayOfPreviousMonth(new Date(), -2, null)); System.out.println("計算兩個日期字符串之間的天數: "+ CalendarHelper.getIntervalDay("2016-03-01", todayStr)); } }
測試結果打印爲:github
today is: 2016-03-15 check is today: true today is (Chinese format): 3月15日 今天所在周的週一: 2016-03-14 今天所在周的週末: 2016-03-20 指定日期的格式化的月,中文的月份: 三月 獲取輸入日期所在月的開始日期: 2016-03-01 獲取輸入日期所在月的結束日期: 2016-03-31 得到指定日期與指定週數間隔的那週週一的日期: 2016-03-28 得到指定日期與指定週數間隔的那週週末的日期: 2016-03-06 獲取輸入日期和間隔月份所在月的開始日期: 2016-05-01 獲取輸入日期和間隔月份所在月的最後日期: 2016-01-31 計算兩個日期字符串之間的天數: 15