今天沒什麼事情作,溫習一下基本知識,在網上看到和日期處理的相關框架,什麼joda,date4j等,都宣稱超級強大簡單易用。下下來試了下,確實都挺不錯。不過本身不是常常涉及到日期操做,且涉及到的也不復雜。且不說這些庫的功能強不強大,單說爲了處理個時間就引入幾十個類,實在有點浪費了。再說JDK提供的Calendar和SimpleDateFormat組合使用功能也仍是很是強大啊。若是以爲同時使用這兩個類稍顯麻煩,能夠稍微封裝一下,便可知足大部分需求,就一個類,本身須要用到什麼功能的時候,添加進去就好了。java
1 package luojing.date; 2 3 import java.io.Serializable; 4 import java.text.ParseException; 5 import java.text.SimpleDateFormat; 6 import java.util.Calendar; 7 import java.util.Date; 8 import java.util.TimeZone; 9 10 /** 11 * 日期時間處理封裝 12 * 13 * @author luojing 14 */ 15 public class DateTime implements Comparable<DateTime>, Serializable { 16 17 private static final long serialVersionUID = 4715414577633839197L; 18 private Calendar calendar = Calendar.getInstance(); 19 private SimpleDateFormat sdf = new SimpleDateFormat(); 20 21 private final String DEFAULT_DATETIME_PATTERN = "yyyy-MM-dd HH:mm:ss"; 22 private final String DEFAULT_DATE_PATTERN = "yyyy-MM-dd"; 23 private final String DEFAULT_TIME_PATTERN = "HH:mm:ss"; 24 25 public DateTime() { 26 } 27 28 public DateTime(String dateStr) { 29 try { 30 parse(dateStr); 31 } catch (Exception e) { 32 e.printStackTrace(); 33 } 34 } 35 36 public DateTime(String dateStr, TimeZone timeZone) { 37 this(dateStr); 38 calendar.setTimeZone(timeZone); 39 } 40 41 public DateTime(String dateStr, String pattern) { 42 try { 43 parse(dateStr, pattern); 44 } catch (Exception e) { 45 e.printStackTrace(); 46 } 47 } 48 49 public DateTime(String dateStr, String pattern, TimeZone timeZone) { 50 this(dateStr, pattern); 51 calendar.setTimeZone(timeZone); 52 } 53 54 public DateTime(int year, int month, int day, int hour, int minute, int second) { 55 calendar.set(year, month, day, hour, minute, second); 56 } 57 58 public DateTime(int year, int month, int day, int hour, int minute, int second, TimeZone timeZone) { 59 this(year, month, day, hour, minute, second); 60 calendar.setTimeZone(timeZone); 61 } 62 63 public DateTime(long milliSeconds) { 64 calendar.setTimeInMillis(milliSeconds); 65 } 66 67 public Calendar getCalendar() { 68 return calendar; 69 } 70 71 public void setCalendar(Calendar calendar) { 72 this.calendar = calendar; 73 } 74 75 public Date getDate() { 76 return calendar.getTime(); 77 } 78 79 public void setDate(Date date) { 80 calendar.setTime(date); 81 } 82 83 public int getYear() { 84 return calendar.get(Calendar.YEAR); 85 } 86 87 public void setYear(int year) { 88 calendar.set(Calendar.YEAR, year); 89 } 90 91 public int getMonth() { 92 return calendar.get(Calendar.MONTH); 93 } 94 95 public void setMonth(int month) { 96 calendar.set(Calendar.MONTH, month); 97 } 98 99 public int getDay() { 100 return calendar.get(Calendar.DAY_OF_MONTH); 101 } 102 103 public void setDay(int dayOfMonth) { 104 calendar.set(Calendar.DAY_OF_MONTH, dayOfMonth); 105 } 106 107 public int getHour() { 108 return calendar.get(Calendar.HOUR_OF_DAY); 109 } 110 111 public void setHour(int hour) { 112 calendar.set(Calendar.HOUR_OF_DAY, hour); 113 } 114 115 public int getMinute() { 116 return calendar.get(Calendar.MINUTE); 117 } 118 119 public void setMinute(int minute) { 120 calendar.set(Calendar.MINUTE, minute); 121 } 122 123 public int getSecond() { 124 return calendar.get(Calendar.SECOND); 125 } 126 127 public void setSecond(int second) { 128 calendar.set(Calendar.SECOND, second); 129 } 130 131 public long getTimeInMilliSeconds() { 132 return calendar.getTimeInMillis(); 133 } 134 135 public void setTimeInMilliSeconds(long milliSeconds) { 136 calendar.setTimeInMillis(milliSeconds); 137 } 138 139 public TimeZone getTimeZone() { 140 return calendar.getTimeZone(); 141 } 142 143 public void setTimeZone(TimeZone timeZone) { 144 calendar.setTimeZone(timeZone); 145 } 146 147 /** 148 * 使用默認格式解析日期字符串 149 * 150 * @param dateStr 151 * @throws Exception 152 */ 153 public void parse(String dateStr) throws Exception { 154 try { 155 parse(dateStr, DEFAULT_DATETIME_PATTERN); 156 } catch (Exception e) { 157 try { 158 parse(dateStr, DEFAULT_DATE_PATTERN); 159 } catch (Exception e1) { 160 try { 161 parse(dateStr, DEFAULT_TIME_PATTERN); 162 } catch (Exception e2) { 163 throw new Exception("the date string [" + dateStr + "] could not be parsed"); 164 } 165 } 166 } 167 168 } 169 170 /** 171 * 使用給定模式解析日期字符串 172 * 173 * @param dateStr 174 * @param pattern 175 * @throws Exception 176 */ 177 public void parse(String dateStr, String pattern) throws Exception { 178 if (dateStr == null) { 179 throw new NullPointerException("date string could not be null"); 180 } 181 182 if (pattern == null) { 183 throw new NullPointerException("the pattern string could not be null"); 184 } 185 186 try { 187 sdf.applyPattern(pattern); 188 sdf.parse(dateStr); 189 } catch (ParseException e) { 190 throw new Exception("the date string [" + dateStr + "] could not be parsed with the pattern [" + pattern + "]"); 191 } 192 calendar = sdf.getCalendar(); 193 } 194 195 /** 196 * 格式化當前DateTime對象表明的時間 197 * 198 * @param pattern 199 * @return 200 */ 201 public String format(String pattern) { 202 sdf.applyPattern(pattern); 203 return sdf.format(calendar.getTime()); 204 } 205 206 /** 207 * 獲取默認格式日期字符串 208 * 209 * @return 210 */ 211 public String toDateTimeString() { 212 sdf.applyPattern(DEFAULT_DATETIME_PATTERN); 213 return sdf.format(calendar.getTime()); 214 } 215 216 @Override 217 public int compareTo(DateTime otherDateTime) { 218 return calendar.compareTo(otherDateTime.getCalendar()); 219 } 220 221 /** 222 * 是否閏年 223 * 224 * @return 225 */ 226 public boolean isLeapYear() { 227 int year = getYear(); 228 boolean result = false; 229 if (year % 100 == 0) { 230 if (year % 400 == 0) { 231 result = true; 232 } 233 } else if (year % 4 == 0) { 234 result = true; 235 } 236 return result; 237 } 238 239 /** 240 * 獲取星期 241 * 242 * @return 243 */ 244 public int getDayOfWeek() { 245 return calendar.get(Calendar.DAY_OF_WEEK); 246 } 247 248 /** 249 * 是否週末 250 * 251 * @return 252 */ 253 public boolean isWeekend() { 254 int dayOfWeek = getDayOfWeek(); 255 return dayOfWeek == 1 || dayOfWeek == 7; 256 } 257 258 /** 259 * 當前DateTime對象月份天數 260 * 261 * @return 262 */ 263 public int getDayNumsInMonth() { 264 Calendar c = (Calendar) calendar.clone(); 265 c.set(Calendar.DAY_OF_MONTH, 1); 266 c.roll(Calendar.DAY_OF_MONTH, -1); 267 return c.get(Calendar.DAY_OF_MONTH); 268 } 269 270 /** 271 * 兩個日期之間間隔天數 272 * 273 * @param otherDateTime 274 * @return 275 */ 276 public int dayNumFrom(DateTime otherDateTime) { 277 long millis = Math.abs(getTimeInMilliSeconds() - otherDateTime.getTimeInMilliSeconds()); 278 int days = (int) Math.floor(millis / 86400000); 279 return days; 280 } 281 282 public boolean lessThan(DateTime otherDateTime) { 283 return compareTo(otherDateTime) < 0; 284 } 285 286 public boolean greaterThan(DateTime otherDateTime) { 287 return compareTo(otherDateTime) > 0; 288 } 289 290 public boolean equal(DateTime otherDateTime) { 291 return compareTo(otherDateTime) == 0; 292 } 293 294 /** 295 * 當前時間基礎上增長秒數(負數時爲減) 296 * 297 * @param amount 298 */ 299 public void plusSecond(int amount) { 300 calendar.add(Calendar.SECOND, amount); 301 } 302 303 public void plusMinute(int amount) { 304 calendar.add(Calendar.MINUTE, amount); 305 } 306 307 public void plusHour(int amount) { 308 calendar.add(Calendar.HOUR, amount); 309 } 310 311 public void plusDays(int amount) { 312 calendar.add(Calendar.DAY_OF_MONTH, amount); 313 } 314 315 public void plusMonth(int amount) { 316 calendar.add(Calendar.MONTH, amount); 317 } 318 319 public void plusYear(int amount) { 320 calendar.add(Calendar.YEAR, amount); 321 } 322 323 public void plus(int year, int month, int day, int hour, int minute, int second) { 324 plusYear(year); 325 plusMonth(month); 326 plusDays(day); 327 plusHour(hour); 328 plusMinute(minute); 329 plusSecond(second); 330 } 331 332 }
測試:app
1 package luojing.date; 2 3 import java.util.Date; 4 5 public class DateTimeTest { 6 7 public static void main(String[] args) throws Exception { 8 DateTime dateTime = new DateTime(); 9 DateTime dateTime2 = new DateTime("2013-12-12"); 10 System.out.println("默認格式輸出:" + dateTime.toDateTimeString()); 11 System.out.println("是否閏年:" + dateTime.isLeapYear()); 12 System.out.println("自定義格式輸出:" + dateTime.format("yyyy-MM-dd")); 13 System.out.println("輸出到毫秒:" + dateTime.format("yyyy-MM-dd HH:mm:ss.SSS")); 14 System.out.println("某月天數:" + dateTime.getDayNumsInMonth()); 15 System.out.println("星期:" + dateTime.getDayOfWeek());//1:星期日,7:星期六 16 System.out.println("是否週末:" + dateTime.isWeekend()); 17 System.out.println("相距:" + dateTime.dayNumFrom(dateTime2) + "天"); 18 19 dateTime.plusMonth(1); 20 System.out.println("增長一個月後的datetime: " + dateTime.toDateTimeString()); 21 dateTime.plus(0, 0, 2, 4, 4, 5); 22 System.out.println("增長 XXX後的datetime: " + dateTime.toDateTimeString()); 23 System.out.println("毫秒數:" + dateTime.getTimeInMilliSeconds()); 24 25 //DateTime轉換爲Date 26 Date date = dateTime.getDate(); 27 System.out.println( dateTime.getTimeInMilliSeconds() == date.getTime()); 28 } 29 }
輸出:框架
默認格式輸出: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
本人使用到日期處理相關的操做,大多就是格式化時間和時間之間的比較。這個封裝已經徹底可以知足個人平常須要了,再說,即便找不到合適的封裝方法,還能夠直接獲取包裝的calendar對象來作處理。less