java日期處理簡單封裝
今天沒什麼事情做,溫習一下基本知識,在網上看到和日期處理的相關框架,什麼joda,date4j等,都宣稱超級強大簡單易用。下下來試了下,確實都挺不錯。不過自己不是經常涉及到日期操作,且涉及到的也不復雜。且不說這些庫的功能強不強大,單說為了處理個時間就引入幾十個類,實在有點浪費了。再說JDK提供的Calendar和SimpleDateFormat組合使用功能也還是非常強大啊。如果覺得同時使用這兩個類稍顯麻煩,可以稍微封裝一下,即可滿足大部分需求,就一個類,自己需要用到什麼功能的時候,新增進去就行了。
測試:package luojing.date; import java.io.Serializable; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; import java.util.TimeZone; /** * 日期時間處理封裝 * * @author luojing */ public class DateTime implements Comparable<DateTime>, Serializable { private static final long serialVersionUID = 4715414577633839197L; private Calendar calendar = Calendar.getInstance(); private SimpleDateFormat sdf = new SimpleDateFormat(); private final String DEFAULT_DATETIME_PATTERN = "yyyy-MM-dd HH:mm:ss"; private final String DEFAULT_DATE_PATTERN = "yyyy-MM-dd"; private final String DEFAULT_TIME_PATTERN = "HH:mm:ss"; public DateTime() { } public DateTime(String dateStr) { try { parse(dateStr); } catch (Exception e) { e.printStackTrace(); } } public DateTime(String dateStr, TimeZone timeZone) { this(dateStr); calendar.setTimeZone(timeZone); } public DateTime(String dateStr, String pattern) { try { parse(dateStr, pattern); } catch (Exception e) { e.printStackTrace(); } } public DateTime(String dateStr, String pattern, TimeZone timeZone) { this(dateStr, pattern); calendar.setTimeZone(timeZone); } public DateTime(int year, int month, int day, int hour, int minute, int second) { calendar.set(year, month, day, hour, minute, second); } public DateTime(int year, int month, int day, int hour, int minute, int second, TimeZone timeZone) { this(year, month, day, hour, minute, second); calendar.setTimeZone(timeZone); } public DateTime(long milliSeconds) { calendar.setTimeInMillis(milliSeconds); } public Calendar getCalendar() { return calendar; } public void setCalendar(Calendar calendar) { this.calendar = calendar; } public Date getDate() { return calendar.getTime(); } public void setDate(Date date) { calendar.setTime(date); } public int getYear() { return calendar.get(Calendar.YEAR); } public void setYear(int year) { calendar.set(Calendar.YEAR, year); } public int getMonth() { return calendar.get(Calendar.MONTH); } public void setMonth(int month) { calendar.set(Calendar.MONTH, month); } public int getDay() { return calendar.get(Calendar.DAY_OF_MONTH); } public void setDay(int dayOfMonth) { calendar.set(Calendar.DAY_OF_MONTH, dayOfMonth); } public int getHour() { return calendar.get(Calendar.HOUR_OF_DAY); } public void setHour(int hour) { calendar.set(Calendar.HOUR_OF_DAY, hour); } public int getMinute() { return calendar.get(Calendar.MINUTE); } public void setMinute(int minute) { calendar.set(Calendar.MINUTE, minute); } public int getSecond() { return calendar.get(Calendar.SECOND); } public void setSecond(int second) { calendar.set(Calendar.SECOND, second); } public long getTimeInMilliSeconds() { return calendar.getTimeInMillis(); } public void setTimeInMilliSeconds(long milliSeconds) { calendar.setTimeInMillis(milliSeconds); } public TimeZone getTimeZone() { return calendar.getTimeZone(); } public void setTimeZone(TimeZone timeZone) { calendar.setTimeZone(timeZone); } /** * 使用預設格式解析日期字串 * * @param dateStr * @throws Exception */ public void parse(String dateStr) throws Exception { try { parse(dateStr, DEFAULT_DATETIME_PATTERN); } catch (Exception e) { try { parse(dateStr, DEFAULT_DATE_PATTERN); } catch (Exception e1) { try { parse(dateStr, DEFAULT_TIME_PATTERN); } catch (Exception e2) { throw new Exception("the date string [" + dateStr + "] could not be parsed"); } } } } /** * 使用給定模式解析日期字串 * * @param dateStr * @param pattern * @throws Exception */ public void parse(String dateStr, String pattern) throws Exception { if (dateStr == null) { throw new NullPointerException("date string could not be null"); } if (pattern == null) { throw new NullPointerException("the pattern string could not be null"); } try { sdf.applyPattern(pattern); sdf.parse(dateStr); } catch (ParseException e) { throw new Exception("the date string [" + dateStr + "] could not be parsed with the pattern [" + pattern + "]"); } calendar = sdf.getCalendar(); } /** * 格式化當前DateTime物件代表的時間 * * @param pattern * @return */ public String format(String pattern) { sdf.applyPattern(pattern); return sdf.format(calendar.getTime()); } /** * 獲取預設格式日期字串 * * @return */ public String toDateTimeString() { sdf.applyPattern(DEFAULT_DATETIME_PATTERN); return sdf.format(calendar.getTime()); } @Override public int compareTo(DateTime otherDateTime) { return calendar.compareTo(otherDateTime.getCalendar()); } /** * 是否閏年 * * @return */ public boolean isLeapYear() { int year = getYear(); boolean result = false; if (year % 100 == 0) { if (year % 400 == 0) { result = true; } } else if (year % 4 == 0) { result = true; } return result; } /** * 獲取星期 * * @return */ public int getDayOfWeek() { return calendar.get(Calendar.DAY_OF_WEEK); } /** * 是否週末 * * @return */ public boolean isWeekend() { int dayOfWeek = getDayOfWeek(); return dayOfWeek == 1 || dayOfWeek == 7; } /** * 當前DateTime物件月份天數 * * @return */ public int getDayNumsInMonth() { Calendar c = (Calendar) calendar.clone(); c.set(Calendar.DAY_OF_MONTH, 1); c.roll(Calendar.DAY_OF_MONTH, -1); return c.get(Calendar.DAY_OF_MONTH); } /** * 兩個日期之間間隔天數 * * @param otherDateTime * @return */ public int dayNumFrom(DateTime otherDateTime) { long millis = Math.abs(getTimeInMilliSeconds() - otherDateTime.getTimeInMilliSeconds()); int days = (int) Math.floor(millis / 86400000); return days; } public boolean lessThan(DateTime otherDateTime) { return compareTo(otherDateTime) < 0; } public boolean greaterThan(DateTime otherDateTime) { return compareTo(otherDateTime) > 0; } public boolean equal(DateTime otherDateTime) { return compareTo(otherDateTime) == 0; } /** * 當前時間基礎上增加秒數(負數時為減) * * @param amount */ public void plusSecond(int amount) { calendar.add(Calendar.SECOND, amount); } public void plusMinute(int amount) { calendar.add(Calendar.MINUTE, amount); } public void plusHour(int amount) { calendar.add(Calendar.HOUR, amount); } public void plusDays(int amount) { calendar.add(Calendar.DAY_OF_MONTH, amount); } public void plusMonth(int amount) { calendar.add(Calendar.MONTH, amount); } public void plusYear(int amount) { calendar.add(Calendar.YEAR, amount); } public void plus(int year, int month, int day, int hour, int minute, int second) { plusYear(year); plusMonth(month); plusDays(day); plusHour(hour); plusMinute(minute); plusSecond(second); } }
package luojing.date; import java.util.Date; public class DateTimeTest { public static void main(String[] args) throws Exception { DateTime dateTime = new DateTime(); DateTime dateTime2 = new DateTime("2013-12-12"); System.out.println("預設格式輸出:" + dateTime.toDateTimeString()); System.out.println("是否閏年:" + dateTime.isLeapYear()); System.out.println("自定義格式輸出:" + dateTime.format("yyyy-MM-dd")); System.out.println("輸出到毫秒:" + dateTime.format("yyyy-MM-dd HH:mm:ss.SSS")); System.out.println("某月天數:" + dateTime.getDayNumsInMonth()); System.out.println("星期:" + dateTime.getDayOfWeek());//1:星期日,7:星期六 System.out.println("是否週末:" + dateTime.isWeekend()); System.out.println("相距:" + dateTime.dayNumFrom(dateTime2) + "天"); dateTime.plusMonth(1); System.out.println("增加一個月後的datetime: " + dateTime.toDateTimeString()); dateTime.plus(0, 0, 2, 4, 4, 5); System.out.println("增加 XXX後的datetime: " + dateTime.toDateTimeString()); System.out.println("毫秒數:" + dateTime.getTimeInMilliSeconds()); //DateTime轉換為Date Date date = dateTime.getDate(); System.out.println( dateTime.getTimeInMilliSeconds() == date.getTime()); } }
輸出:
預設格式輸出:2013-09-25 19:16:15
是否閏年:false
自定義格式輸出:2013-09-25
輸出到毫秒:2013-09-25 19:16:15.278
某月天數:30
星期:4
是否週末:false
相距:77天
增加一個月後的datetime: 2013-10-25 19:16:15
增加 XXX後的datetime: 2013-10-27 23:20:20
毫秒數:1382887220278
true