在以前的項目中,常常會遇到Calendar,Date的一些操做時間的類,而且總會遇到時間日期之間的格式轉化問題,雖然作完了可是老是忘記,記不清楚,每次還都要查找資料。今天總結一下,加深印象。java
Calendarsql
Calendar是java.util 包下面的一個抽象類,它爲特定瞬間與一組諸如YEAR、MONTH、DAY_OF_MONTH、HOUR等日曆字段之間的轉換提供了一些方法,並未操做日曆字段(例如得到下星期的日期)提供了一些方法。瞬間值可用毫秒值來表示,它是距格林威治標準時間 1970 年1月 1日的 00:00:00:000的偏移量。apache
Java API 中說到,Calendar提供了一個類方法getInstance,以此得到此類型的一個通用對象,Calendar的getInstance返回一個Calendar對象,其日曆字段值已由當前日期和時間初始化。咱們知道,抽象類是不可以被實例化的,那爲何會返回一個Calendar對象呢?Calendar還有一個直接子類GregorianCalendar,這個類是Calendar的實現類,那麼其實getInstance方法返回的是Calendar的子類GregorianCalendar的對象。編程
Calendar對日曆字段的操做有三種方法:api
set() ,add() , roll()ide
set(f,value),這個方法的含義是把日曆字段f設置成value,api中說到,它設置了一個內部的成員變量,以指示f發生了改變,可是直到調用get()
、getTime()
、getTimeInMillis()
、add()
或 roll()
時纔會從新計算日曆的時間值(以毫秒爲單位)。函數
add(f,delate),將delate添加到f字段中,這至關因而set(f,get(f)+delate),固然,這樣改動的話,可能日曆的其餘字段也會發生相應的改變,與 set()
不一樣,add()
強迫日曆系統當即從新計算日曆的毫秒數和全部字段。spa
roll(f,value)與add(f,delate)的區別 :在完成調用後,更大的字段無變化code
在項目中,常常看見的是經過Calendar對象獲得當前的年月日。orm
下面經過一個小小的例子看看是如何獲得年月日的
import java.util.Calendar; public class CalendarTest { public static void main(String[] args) { Calendar cal= Calendar.getInstance(); int day= cal.get(Calendar.DATE); int month=cal.get(Calendar.MONTH)+1; int year=cal.get(Calendar.YEAR); String[] weekDays = {"星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六"}; int w = cal.get(Calendar.DAY_OF_WEEK) - 1; if (w < 0) w = 0; System.out.println( year+"年"+month+"月"+day+"號,"+weekDays[w]); } }
此代碼輸出的是2017年6月15號,星期四
爲何month要加1才能獲得當前月份呢?
是由於在格里高利曆和羅馬儒略曆中一年中的第一個月是 JANUARY,它爲 0;最後一個月取決於一年中的月份數。 簡單來講,由於這個值的初始值是0,所以咱們要用它來表示正確的月份時就須要加1。
爲何week要減1呢?
這是由於一個星期中的第一天是SunDay,從星期日到星期六,對應的數字分別是1,2,3,4,5,6,7,因此須要減1。
Calendar還有其餘的一些方法,好比getTimeMillis(),返回Calendar的時間值,以毫秒計算
getTime(),返回一個此Calendar的時間值的Date對象,和new Date()的值是同樣的。
Date
Date也是java.util包下的一個類,類 表示特定的瞬間,精確到毫秒。
從 JDK 1.1 開始,應該使用 類實現日期和時間字段之間轉換,使用 類來格式化和解析日期字符串。 中的相應方法已廢棄。
SimpleDateFormat
SimpleDateFormat 是一個以與語言環境有關的方式來格式化和解析日期的具體類。
SimpleDateFormat是DateFormat抽象類的實現類,DateFormat繼承Format,Format定義了編程接口,用於將語言環境敏感的對象格式化爲 (使用 方法)和將 從新解析爲對象(使用 方法)。
DateCalendarDateFormatDateStringformatStringparseObject
在格式化日期的時候,常常用到的構造方法是帶一個String參數的
Public SimpleDateFormat(String pattern)
這個構造函數的意思是用給定的模式和默認的語言環境構的日期格式符號來格式化。
SimpleDateFormat中有format方法和pase方法,format方法是將Date對象轉化爲String字符串,pase是將字符串轉化爲Date對象。
下面經過代碼來展現日期和字符串之間的轉化。
假如我要將一個日期類型的時間格式轉化成"yyyy-mm-dd"類型的字符串,須要用到format方法,
Date date=new Date();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-mm-dd");
sdf.format(date);
若是須要將"yyyy-mm-dd"String類型的日期轉化成日期對象類型,就須要用到parse,
String str= "2017-6-17"
sdf.parse(str),這樣就能夠獲得一個日期類型。
附上項目當中的時間轉換的util,裏面包含了對時間的各類轉化。
1 import java.sql.Timestamp; 2 import java.text.ParseException; 3 import java.text.SimpleDateFormat; 4 import java.util.Calendar; 5 import java.util.Date; 6 import java.util.Locale; 7 import java.util.TimeZone; 8 9 import org.apache.commons.lang3.StringUtils; 10 11 public final class DateUtil { 12 // 默認顯示日期的格式 13 public static final String DATAFORMAT_STR = "yyyy-MM-dd"; 14 // 默認顯示日期的格式 15 public static final String YYYY_MM_DATAFORMAT_STR = "yyyy-MM"; 16 // 默認顯示日期時間的格式 17 public static final String DATATIMEF_STR = "yyyy-MM-dd HH:mm:ss"; 18 // 默認顯示日期時間的格式 19 public static final String DATATIMEF_STR2 = "yyyyMMdd HH:mm:ss"; 20 // 默認顯示日期時間的格式 精確到毫秒 21 public static final String DATATIMEF_STR_MIS = "yyyyMMddHHmmssSSS"; 22 // 默認顯示日期時間的格式 精確到分鐘 23 public static final String DATATIMEF_STR_MI = "yyyy-MM-dd HH:mm"; 24 25 public static final String DATATIMEF_STR_MDHm = "MM.dd HH:mm"; 26 27 public static final String HH_STR = "HH"; 28 29 // 精確到秒 30 public static final String DATATIMEF_STR_SEC = "yyyyMMddHHmmss"; 31 // 默認顯示簡體中文日期的格式 32 public static final String ZHCN_DATAFORMAT_STR = "yyyy年MM月dd日"; 33 // 默認顯示簡體中文日期時間的格式 34 public static final String ZHCN_DATATIMEF_STR = "yyyy年MM月dd日HH時mm分ss秒"; 35 // 默認顯示簡體中文日期時間的格式 36 public static final String ZHCN_DATATIMEF_STR_4yMMddHHmm = "yyyy年MM月dd日HH時mm分"; 37 38 // 默認顯示月份和日期的格式 39 public static final String MONTHANDDATE_STR = "MM.dd"; 40 41 public static final String DATATIMEF_STR_MIN = "yyyyMMddHHmm"; 42 43 public static final String HOUR_END = " 23:59:59"; 44 45 public static final String HOUR_START = " 00:00:00"; 46 47 private DateUtil() { 48 } 49 50 public static Date now() { 51 52 return Calendar.getInstance(Locale.CHINESE).getTime(); 53 } 54 55 public static Date daysAfter(Date baseDate, int increaseDate) { 56 Calendar calendar = Calendar.getInstance(Locale.CHINESE); 57 calendar.setTime(baseDate); 58 calendar.add(Calendar.DATE, increaseDate); 59 return calendar.getTime(); 60 } 61 62 public static Date hoursAfter(Date baseDate, int increaseHours) { 63 Calendar calendar = Calendar.getInstance(Locale.CHINESE); 64 calendar.setTime(baseDate); 65 calendar.add(Calendar.HOUR_OF_DAY, increaseHours); 66 return calendar.getTime(); 67 } 68 69 public static Date minuteAfter(Date baseDate, int increaseMonths) { 70 Calendar calendar = Calendar.getInstance(Locale.CHINESE); 71 calendar.setTime(baseDate); 72 calendar.add(Calendar.MINUTE, increaseMonths); 73 return calendar.getTime(); 74 } 75 76 public static Date monthAfter(Date baseDate, int increaseMonths) { 77 Calendar calendar = Calendar.getInstance(Locale.CHINESE); 78 calendar.setTime(baseDate); 79 calendar.add(Calendar.MONTH, increaseMonths); 80 return calendar.getTime(); 81 } 82 83 public static Date getInternalDateByDay(Date d, int days) { 84 Calendar now = Calendar.getInstance(TimeZone.getDefault()); 85 now.setTime(d); 86 now.add(Calendar.DATE, days); 87 return now.getTime(); 88 } 89 90 public static Date getInternalDateByMinute(Date d, int minutes) { 91 Calendar now = Calendar.getInstance(TimeZone.getDefault()); 92 now.setTime(d); 93 now.add(Calendar.MINUTE, minutes); 94 return now.getTime(); 95 } 96 97 /** 98 * 將Date轉換成字符串「yyyy-mm-dd hh:mm:ss」的字符串 99 * 100 * @param date 101 * @return 102 */ 103 public static String dateToDateString(Date date) { 104 return dateToDateString(date, DATATIMEF_STR); 105 } 106 107 /** 108 * 將Date轉換成字符串「yyyy-mm-dd hh:mm:ss」的字符串 109 * 110 * @param date 111 * @return 112 */ 113 public static String dateToDateString2(Date date) { 114 return dateToDateString(date, DATATIMEF_STR2); 115 } 116 117 /** 118 * 將Date轉換成formatStr格式的字符串 119 * 120 * @param date 121 * @param formatStr 122 * @return 123 */ 124 public static String dateToDateString(Date date, String formatStr) { 125 if (date == null) { 126 return null; 127 } 128 java.text.DateFormat df = getDateFormat(formatStr); 129 return date != null ? df.format(date) : ""; 130 } 131 132 /** 133 * 按照默認formatStr的格式,轉化dateTimeStr爲Date類型 dateTimeStr必須是formatStr的形式 134 * 135 * @param dateTimeStr 136 * @param formatStr 137 * @return 138 */ 139 public static Date getDate(String dateTimeStr, String formatStr) { 140 try { 141 if (dateTimeStr == null || dateTimeStr.equals("")) { 142 return null; 143 } 144 java.text.DateFormat sdf = new SimpleDateFormat(formatStr); 145 java.util.Date d = sdf.parse(dateTimeStr); 146 return d; 147 } catch (ParseException e) { 148 throw new RuntimeException(e); 149 } 150 } 151 152 public static String getCurDate() { 153 return dateToDateString(Calendar.getInstance().getTime(), 154 DATAFORMAT_STR); 155 } 156 157 public static String getCurHour() { 158 return dateToDateString(Calendar.getInstance().getTime(), HH_STR); 159 } 160 161 public static int getThisMonth() { 162 Calendar c = Calendar.getInstance(Locale.CHINESE); 163 int month = c.get(Calendar.MONTH) + 1; 164 return month; 165 166 } 167 168 public static int getThisWeek() { 169 Calendar c = Calendar.getInstance(Locale.CHINESE); 170 c.setFirstDayOfWeek(Calendar.MONDAY); 171 int week = c.get(Calendar.WEEK_OF_YEAR); 172 return week; 173 174 } 175 176 public static SimpleDateFormat getDateFormat(final String formatStr) { 177 return new SimpleDateFormat(formatStr); 178 } 179 180 @SuppressWarnings("deprecation") 181 public static String getFirstDateOfMonth(Date now) { 182 SimpleDateFormat df1 = new SimpleDateFormat(DATATIMEF_STR); 183 Date da = new Date(now.getYear(), now.getMonth(), 01); 184 return df1.format(da); 185 } 186 187 @SuppressWarnings("deprecation") 188 public static String getLastDateOfMonth(Date now) { 189 SimpleDateFormat df1 = new SimpleDateFormat(DATATIMEF_STR); 190 Date da = new Date(now.getYear(), now.getMonth(), 31); 191 return df1.format(da); 192 } 193 194 /** 195 * 獲取兩個毫秒間隔的分鐘 196 * 197 * @param t1 198 * @param t2 199 * @return 200 */ 201 public static int getMinutesBetweenMillis(long t1, long t2) { 202 return (int) ((t1 - t2) / (60 * 1000)); 203 } 204 205 /** 206 * 判斷目標時間是否處於某一時間段內 207 * 208 * @param target 209 * @param begin 210 * @param end 211 * @return 212 */ 213 public static boolean compareTargetTime(Date target, String begin, 214 String end) { 215 // 格式化時間 暫時不考慮傳入參數的判斷,其餘地方若是要調用,最好擴展判斷一下入參問題 216 String targetTime = dateToDateString(target, DATATIMEF_STR).substring( 217 11);// HH:mm:ss 218 if (targetTime.compareTo(begin) >= 0 && end.compareTo(targetTime) >= 0) { 219 return true; 220 } 221 return false; 222 } 223 224 /** 225 * 226 * @param time1 227 * @param timw2 228 * @return time1 小於 time 2 返回 true 229 */ 230 public static boolean compareTime(Date time1, Date time2) { 231 long start = time1.getTime(); 232 long end = time2.getTime(); 233 if (start < end) { 234 return true; 235 } 236 237 return false; 238 } 239 240 /** 241 * 取得兩個時間段的時間間隔 return t2 與t1的間隔天數 throws ParseException 242 * 若是輸入的日期格式不是0000-00-00 格式拋出異常 243 */ 244 public static int getBetweenDays(String t1, String t2) 245 throws ParseException { 246 SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd"); 247 int betweenDays = 0; 248 Date d1 = format.parse(t1); 249 Date d2 = format.parse(t2); 250 Calendar c1 = Calendar.getInstance(); 251 Calendar c2 = Calendar.getInstance(); 252 c1.setTime(d1); 253 c2.setTime(d2); 254 // 保證第二個時間必定大於第一個時間 255 if (c1.after(c2)) { 256 c1 = c2; 257 c2.setTime(d1); 258 } 259 int betweenYears = c2.get(Calendar.YEAR) - c1.get(Calendar.YEAR); 260 betweenDays = c2.get(Calendar.DAY_OF_YEAR) 261 - c1.get(Calendar.DAY_OF_YEAR); 262 for (int i = 0; i < betweenYears; i++) { 263 c1.set(Calendar.YEAR, (c1.get(Calendar.YEAR) + 1)); 264 betweenDays += c1.getMaximum(Calendar.DAY_OF_YEAR); 265 } 266 return betweenDays; 267 } 268 269 /** 270 * 格式化時間 yyyy-MM-dd 271 * 272 * @return 273 */ 274 public static String getFormatDate(Date date) { 275 return new SimpleDateFormat().format(date); 276 } 277 278 /** 279 * 按照默認formatStr的格式,轉化dateTimeStr爲Date類型 dateTimeStr必須是formatStr的形式 280 * 281 * @param dateTimeStr 282 * @param formatStr 283 * @return 284 */ 285 public static Date getFormatDate(Date dateTimer, String formatStr) { 286 try { 287 if (dateTimer == null) { 288 return null; 289 } 290 java.text.DateFormat sdf = new SimpleDateFormat(formatStr); 291 String timeStr = sdf.format(dateTimer); 292 Date formateDate = sdf.parse(timeStr); 293 return formateDate; 294 } catch (ParseException e) { 295 throw new RuntimeException(e); 296 } 297 } 298 299 /** 300 * 獲取兩個時間之間相差的天數 301 * 302 * @param time1 303 * @param time2 304 * @return 305 */ 306 public static long getQuot(String time1, String time2) { 307 long quot = 0; 308 SimpleDateFormat ft = new SimpleDateFormat("yyyy-MM-dd"); 309 try { 310 Date date1 = ft.parse(time1); 311 Date date2 = ft.parse(time2); 312 quot = date1.getTime() - date2.getTime(); 313 quot = quot / 1000 / 60 / 60 / 24; 314 } catch (ParseException e) { 315 e.printStackTrace(); 316 } 317 return quot; 318 } 319 320 public static long getQuot(Date time1, Date time2) { 321 if(time1==null || time2==null) 322 return -1; 323 long quot = 0; 324 quot = time1.getTime() - time2.getTime(); 325 quot = quot / 1000 / 60 / 60 / 24; 326 return quot; 327 } 328 329 /** 330 * 獲取和當前時間相差的分鐘數 331 * 332 * @param begin 333 * @return 334 */ 335 public static long getDiffenceValue(Date begin) { 336 long value = 0; 337 Calendar cal = Calendar.getInstance(); 338 Date now = cal.getTime(); 339 value = (now.getTime() - begin.getTime()) / 1000 / 60; 340 return value; 341 } 342 /** 343 * 獲取和當前時間相差的秒數 344 * 345 * @param begin 346 * @return 347 */ 348 public static long getSecondsValue(Date begin) { 349 long value = 0; 350 Calendar cal = Calendar.getInstance(); 351 Date now = cal.getTime(); 352 value = (now.getTime() - begin.getTime()) / 1000; 353 return value; 354 } 355 356 public static long getMillsBetweenTwoDate(Date date1, Date date2) { 357 return date1.getTime() - date2.getTime(); 358 } 359 360 /** 361 * 求多少天前/後的日期 362 * 363 * @param field 364 * 單位:年,月,日 365 * @param day 366 * 多少天 367 * @return 368 */ 369 public static final Date addDate(int field, int day) { 370 Calendar nowCalendar = Calendar.getInstance(Locale.CHINESE); 371 nowCalendar.setTime(DateUtil.now()); 372 nowCalendar.add(field, day); 373 return nowCalendar.getTime(); 374 } 375 376 /** 377 * 獲取本月第一天 378 * @return 379 */ 380 public static final String getCurrFirstDay(){ 381 SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd"); 382 Calendar c = Calendar.getInstance(); 383 c.add(Calendar.MONTH, 0); 384 c.set(Calendar.DAY_OF_MONTH, 1);// 設置爲1號,當前日期既爲本月第一天 385 String first = format.format(c.getTime()); 386 return first; 387 } 388 389 /** 390 * 獲取本月第一天 391 * @return 392 */ 393 public static final String getCurrLastDay(){ 394 SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd"); 395 //獲取當前月最後一天 396 Calendar ca = Calendar.getInstance(); 397 ca.set(Calendar.DAY_OF_MONTH, ca.getActualMaximum(Calendar.DAY_OF_MONTH)); 398 String last = format.format(ca.getTime()); 399 return last; 400 } 401 402 /** 403 * date類型轉timestamp類型 404 * @return 405 */ 406 public static final Timestamp dateToTimestamp(Date date){ 407 Timestamp time = new Timestamp(date.getTime()); 408 return time; 409 } 410 411 /** 412 * timestamp類型轉date類型 413 * @return 414 */ 415 public static final Date TimestampTodate(Timestamp date){ 416 Date d = new Date(date.getTime()); 417 return d; 418 } 419 420 /** 421 * String類型轉date類型 422 * @return 423 */ 424 public static final Date StringTodate(String date){ 425 if(StringUtils.isNotBlank(date)){ 426 SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); 427 try { 428 return sdf.parse(date); 429 } catch (ParseException e) { 430 return null; 431 } 432 }else{ 433 return null; 434 } 435 } 436 }