首页 > 代码库 > 日期时间操作的工具类

日期时间操作的工具类

  1 /**
  2  * 对日期时间中的相关方法进行分装,主要包括了获取当前时间,已经当前时间中运算关系等方法
  3  */
  4 public class DateTime {
  5 
  6     final static String datePattern = "yyyy-MM-dd HH:mm:ss";
  7     final static String dateonlyPattern = "yyyy-MM-dd";
  8 
  9     final static SimpleDateFormat sf = new SimpleDateFormat(datePattern);
 10     final static SimpleDateFormat dateonlysf = new SimpleDateFormat(dateonlyPattern);
 11     // 时间对应的long值
 12     long nowtime;
 13 
 14     /**
 15      * 以当前系统时间构造DateTime对象
 16      * 
 17      */
 18     public DateTime() {
 19         nowtime = System.currentTimeMillis();
 20     }
 21 
 22     /**
 23      * 以指定时间构造DateTime对象,如果指定的时间不符合格式,将使用 系统当前时间构造对象
 24      * 
 25      * @param time
 26      *            时间格式为yyyy-MM-dd HH:mm:ss的字符串
 27      */
 28     public DateTime(String time) {
 29         this(time, "yyyy-MM-dd HH:mm:ss");
 30     }
 31 
 32     /**
 33      * 以指定时间和指定时间格式构造DateTime对象. 如果指定的时间不符合格式,将使用系统当前时间构造对象
 34      * 
 35      * @param time
 36      *            指定的时间
 37      * @param timePattern
 38      *            指定的日间格式
 39      */
 40     public DateTime(String time, String timePattern) {
 41         try {
 42             SimpleDateFormat sdf = new SimpleDateFormat(timePattern);
 43             Date d = sdf.parse(time);
 44             nowtime = d.getTime();
 45         } catch (ParseException e) {
 46             nowtime = System.currentTimeMillis();
 47         }
 48     }
 49 
 50     /**
 51      * 取回系统当前时间 时间格式yyyy-MM-dd hh:mm:ss
 52      * 
 53      * @return yyyy-MM-dd hh:mm:ss格式的时间字符串
 54      */
 55     public String getNowTime() {
 56         String retValue = http://www.mamicode.com/null;
 57         retValue = http://www.mamicode.com/sf.format(new Date(nowtime));
 58         return retValue;
 59     }
 60 
 61     /**
 62      * 按指定日期、时间格式返回当前日期
 63      * 
 64      * @param datePattern
 65      *            格式字符串
 66      * @return 格式化的日期、时间字符串
 67      */
 68     public String getNowTime(String datePattern) {
 69         String retValue = http://www.mamicode.com/null;
 70         SimpleDateFormat sf = new SimpleDateFormat(datePattern);
 71         retValue = http://www.mamicode.com/sf.format(new Date(nowtime));
 72         return retValue;
 73     }
 74 
 75     /**
 76      * 返回4位的年份,如‘2004‘
 77      * 
 78      * @return 79      */
 80     public String getYear() {
 81         return getNowTime("yyyy");
 82     }
 83 
 84     /**
 85      * 返回月份. 一位的月份数字,如8月将返回8
 86      * 
 87      * @return 月份 如果8月返回8,12月返回12
 88      */
 89     public String getMonth() {
 90 
 91         return getNowTime("M");
 92     }
 93 
 94     /**
 95      * 返回一个月中的第几天
 96      * 
 97      * @return 天 一位的天数,如当前是4月1日将返回‘1‘
 98      */
 99     public String getDay() {
100         return getNowTime("d");
101     }
102 
103     /**
104      * 返回24小时制的小时
105      * 
106      * @return 小时
107      */
108     public String getHour() {
109         return getNowTime("HH");
110     }
111 
112     /**
113      * 返回分钟
114      * 
115      * @return 分钟 一位的分钟数
116      */
117     public String getMinute() {
118         return getNowTime("m");
119     }
120 
121     /**
122      * 返回秒
123      * 
124      * @return 秒 一位的秒数
125      */
126     public String getSecond() {
127         return getNowTime("s");
128     }
129 
130     /**
131      * 返回星期中名称
132      * 
133      * @return 如星期二将返回"星期二"
134      */
135     public String getDayInWeek() {
136         return getNowTime("E");
137     }
138     
139     /**
140      * 返回星期几,
141      * @return 数字星期几,如星期二则返回2,星期天则返回0
142      */
143     public String getNumInWeek(){
144         String dayInWeek = this.getDayInWeek();
145         dayInWeek = dayInWeek.replace("星期", "");
146         
147         char[] chars = dayInWeek.toCharArray();
148         for (int i = 0; i < chars.length; i++) {
149             switch (chars[i]) {
150             case ‘一‘:
151                 chars[i] = ‘1‘;
152                 break;
153             case ‘二‘:
154                 chars[i] = ‘2‘;
155                 break;
156             case ‘三‘:
157                 chars[i] = ‘3‘;
158                 break;
159             case ‘四‘:
160                 chars[i] = ‘4‘;
161                 break;
162             case ‘五‘:
163                 chars[i] = ‘5‘;
164                 break;
165             case ‘六‘:
166                 chars[i] = ‘6‘;
167                 break;
168             case ‘日‘:
169                 chars[i] = ‘0‘;
170                 break;
171             }
172         }
173         return new String(chars);
174     }
175 
176     /**
177      * 只返回日期 如2004-08-12.月份和日期都是两位,不足的在前面补0
178      * 
179      * @return 日期
180      */
181     public String getDateOnly() {
182         return getNowTime("yyyy-MM-dd");
183     }
184     
185 
186 
187     /**
188      * 只返回时间 如12:20:30.时间为24小时制,分钟和秒数都是两位,不足补0
189      * 
190      * @return 时间
191      */
192     public String getTimeOnly() {
193         return getNowTime("HH:mm:ss");
194     }
195 
196     /**
197      * 调整年份
198      * 
199      * @param i
200      *            要调整的基数,正表示加,负表示减
201      */
202     public void adjustYear(int i) {
203         adjustTime(i, 0, 0, 0, 0, 0);
204     }
205 
206     /**
207      * 调整月份
208      * 
209      * @param i
210      *            要调整的基数,正表示加,负表示减
211      */
212     public void adjustMonth(int i) {
213         adjustTime(0, i, 0, 0, 0, 0);
214     }
215 
216     /**
217      * 调整天数
218      * 
219      * @param i
220      *            要调整的基数,正表示加,负表示减
221      */
222     public void adjustDay(int i) {
223         adjustTime(0, 0, i, 0, 0, 0);
224     }
225 
226     /**
227      * 调整小时
228      * 
229      * @param i
230      *            要调整的基数,正表示加,负表示减
231      */
232     public void adjustHour(int i) {
233         adjustTime(0, 0, 0, i, 0, 0);
234     }
235 
236     /**
237      * 调整分数
238      * 
239      * @param i
240      *            要调整的基数,正表示加,负表示减
241      */
242     public void adjustMinute(int i) {
243         adjustTime(0, 0, 0, 0, i, 0);
244     }
245 
246     /**
247      * 调整秒数
248      * 
249      * @param i
250      *            要调整的基数,正表示加,负表示减
251      */
252     public void adjustSecond(int i) {
253         adjustTime(0, 0, 0, 0, 0, i);
254     }
255 
256     /**
257      * 调整时间
258      * 
259      * @param y
260      *            年
261      * @param m
262      *            月
263      * @param d
264      *            日
265      * @param h
266      *            小时
267      * @param mm
268      *            分钟
269      * @param ss
270      *            秒
271      */
272     protected void adjustTime(int y, int m, int d, int h, int mm, int ss) {
273         GregorianCalendar cal = new GregorianCalendar();
274         cal.setTimeInMillis(nowtime);
275         cal.add(Calendar.YEAR, y);
276         cal.add(Calendar.MONTH, m);
277         cal.add(Calendar.DAY_OF_MONTH, d);
278         cal.add(Calendar.HOUR_OF_DAY, h);
279         cal.add(Calendar.MINUTE, mm);
280         cal.add(Calendar.SECOND, ss);
281         nowtime = cal.getTimeInMillis();
282     }
283 
284     /**
285      * 返回当前日期.
286      * 
287      * @return yyyy-MM-dd HH:mm:ss格式的日期/时间
288      */
289     public static String getNowDateTime() {
290         DateTime dt = new DateTime();
291         return dt.getNowTime();
292     }
293 
294     /**
295      * 按指定格式返回当前日期.
296      * 
297      * @param pattern
298      *            时间格式
299      * @return 格式化的日期/时间
300      */
301     public static String getNowDateTime(String pattern) {
302         DateTime dt = new DateTime();
303         return dt.getNowTime(pattern);
304     }
305 
306     /**
307      * 返回中文格式的日期.如"二零零零年八月六日星期五18点4分"
308      * 
309      * @return String
310      */
311     public static String getNowDateTimeChinese() {
312         DateTime dt = new DateTime();
313         return getNowDateTimeChinese("yyyy年M月d日E") + dt.getNowTime("H点mm分");
314     }
315 
316     /**
317      * 根据自定义输出中文日期格式输出字符串。
318      * 
319      * @param pattern
320      *            日期、时间格式. ‘yyyy年MM月dd日E‘将输出‘2004年8月16日星期六‘
321      * @return 时间、日期字符串
322      */
323     public static String getNowDateTimeChinese(String pattern) {
324         DateTime dt = new DateTime();
325         return numberToChinese(dt.getNowTime(pattern));
326     }
327 
328     /**
329      * 返回中文的数字,把12345678转成‘零‘,‘一‘,‘二‘,‘三‘,‘四‘,‘五‘,‘六‘,‘七‘,‘八‘,‘九‘
330      * 
331      * @param n
332      *            要转的字符串
333      * @return 转换后的字符串
334      */
335     public static String numberToChinese(String n) {
336         char[] chars = n.toCharArray();
337         for (int i = 0; i < chars.length; i++) {
338             switch (chars[i]) {
339             case ‘1‘:
340                 chars[i] = ‘一‘;
341                 break;
342             case ‘2‘:
343                 chars[i] = ‘二‘;
344                 break;
345             case ‘3‘:
346                 chars[i] = ‘三‘;
347                 break;
348             case ‘4‘:
349                 chars[i] = ‘四‘;
350                 break;
351             case ‘5‘:
352                 chars[i] = ‘五‘;
353                 break;
354             case ‘6‘:
355                 chars[i] = ‘六‘;
356                 break;
357             case ‘7‘:
358                 chars[i] = ‘七‘;
359                 break;
360             case ‘8‘:
361                 chars[i] = ‘八‘;
362                 break;
363             case ‘9‘:
364                 chars[i] = ‘九‘;
365                 break;
366             case ‘0‘:
367                 chars[i] = ‘零‘;
368                 break;
369             }
370         }
371         return new String(chars);
372     }
373 
374     /**
375      * 按指定格式转换输出指定的日期
376      * 
377      * @param date
378      *            要输出的日期
379      * @param datePattern
380      *            要输出的时间格式
381      * @return 格式化后的字符串
382      */
383     public static String getTime(Date date, String datePattern) {
384         String retValue = http://www.mamicode.com/null;
385         SimpleDateFormat sf = new SimpleDateFormat(datePattern);
386         retValue =http://www.mamicode.com/ sf.format(date);
387         return retValue;
388     }
389 
390     /**
391      * 把字符串格式化成相应的日期格式
392      * 
393      * @param s 日期字符串格式 String
394      * @param datePattern 日期模式 String
395      * @return 返回格式化后的日期
396      */
397     public static Date parseDate(String s, String datePattern) {
398 
399         s = s.replaceAll(" ", "");
400         if (s == null || s.equals(""))
401             return null;
402 
403         Date d = null;
404         SimpleDateFormat sf = new SimpleDateFormat(datePattern);
405         try {
406             d = sf.parse(s);
407         } catch (ParseException e) {
408         }
409         return d;
410     }
411     
412     /**
413      * 把两个时间进行比较得出他们的间隔的天数,如果比较时间大于标准时间,则返回负的天数
414      * 
415      * @param compareTime 待比较的时间 String
416      * 
417      * @param standardTime 标准的时间 String
418      * 
419      * @return 返回比较的结果 int
420      */
421     public int getIntervalDays(String compareTime,String standardTime){
422         int result = 0;
423         Date compareDate = this.parseDate(compareTime, "yyyy-MM-dd");
424         Date standardDate = this.parseDate(standardTime, "yyyy-MM-dd");
425         long sl = compareDate.getTime();
426         long el = standardDate.getTime();
427         long ei = el-sl;
428         result = (int)((ei)/(1000*60*60*24));
429         //cal.set
430         return result;
431     }
432 
433     /**
434      * 返回字符串
435      * 
436      * @see java.lang.Object#toString()
437      */
438     public String toString() {
439         return getNowTime();
440     }
441     /**
442      * 
443      * 功能说明: 把 2012-4-25转化成 二〇一二年〇四月二十五日
444      * @param 字符串 格式 yyyy-mm-dd
445      * @author chh
446      * @Apr 19, 2012
447      */
448     public  String dateToCN(String  srcStr) {     
449         Date date = null;
450         SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd");
451         try {
452             date = sf.parse(srcStr);
453         } catch (ParseException e) {
454         }
455         if (null == date || "".equals(date)) {      
456             return null;      
457         }      
458         String[] CN = { "〇", "一", "二", "三", "四", "五", "六", "七", "八", "九" };    
459         String str = "十";   
460            
461 //        String[] CN = { "零", "壹", "贰", "叁", "肆", "伍", "陆", "柒", "捌", "玖"};    
462 //        String str = "拾";   
463            
464         Calendar calendar = Calendar.getInstance();      
465         calendar.setTime(date);      
466            
467         StringBuffer cn = new StringBuffer();      
468            
469         String year = String.valueOf(calendar.get(Calendar.YEAR));      
470           
471         for (int i = 0; i < year.length(); i++) {      
472             cn.append(CN[year.charAt(i) - 48]);      
473         }      
474           
475         cn.append("年");      
476           
477         int t1,t2;   
478            
479         int mon = calendar.get(Calendar.MONTH) + 1;      
480            
481         t1 = mon/10;   
482         t2 = mon%10;   
483            
484         if(t1 < 10){   
485             if(t1 != 0){   
486                 cn.append(CN[t1]);   
487                 cn.append(str);   
488             }else{   
489                 cn.append(CN[0]);   
490             }   
491         }   
492            
493         if(t2 < 10 && t2 != 0){   
494             cn.append(CN[t2]);   
495         }   
496            
497         cn.append("月");      
498           
499         int day = calendar.get(Calendar.DAY_OF_MONTH);      
500            
501         t1 = day/10;   
502         t2 = day%10;   
503            
504         if(t1 < 10){   
505             if(t1 != 0){   
506                 //一十五 只显示 十五
507                 if(t1!=1){
508                     cn.append(CN[t1]);   
509                 }
510                 cn.append(str);   
511             }else{   
512                 cn.append(CN[0]);   
513             }   
514         }   
515            
516         if(t2 < 10 && t2 != 0){   
517             cn.append(CN[t2]);   
518         }   
519            
520         cn.append("日");      
521           
522         return cn.toString();      
523     }  
524     /**
525      * 
526      * 功能说明:把 2012-4-25转化成 贰零壹贰年零肆月拾伍日
527      * @param 字符串 格式 yyyy-mm-dd
528      * @author chh
529      * @Apr 19, 2012
530      */
531     public  String dateToUppercaseCN(String  srcStr) {     
532         Date date = null;
533         SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd");
534         try {
535             date = sf.parse(srcStr);
536         } catch (ParseException e) {
537         }
538         if (null == date || "".equals(date)) {      
539             return null;      
540         }    
541            
542        String[] CN = { "零", "壹", "贰", "叁", "肆", "伍", "陆", "柒", "捌", "玖"};    
543         String str = "拾";   
544            
545         Calendar calendar = Calendar.getInstance();      
546         calendar.setTime(date);      
547            
548         StringBuffer cn = new StringBuffer();      
549            
550         String year = String.valueOf(calendar.get(Calendar.YEAR));      
551           
552         for (int i = 0; i < year.length(); i++) {      
553             cn.append(CN[year.charAt(i) - 48]);      
554         }      
555           
556         cn.append("年");      
557           
558         int t1,t2;   
559            
560         int mon = calendar.get(Calendar.MONTH) + 1;      
561            
562         t1 = mon/10;   
563         t2 = mon%10;   
564            
565         if(t1 < 10){   
566             if(t1 != 0){   
567                 cn.append(CN[t1]);   
568                 cn.append(str);   
569             }else{   
570                 cn.append(CN[0]);   
571             }   
572         }   
573            
574         if(t2 < 10 && t2 != 0){   
575             cn.append(CN[t2]);   
576         }   
577            
578         cn.append("月");      
579           
580         int day = calendar.get(Calendar.DAY_OF_MONTH);      
581            
582         t1 = day/10;   
583         t2 = day%10;   
584            
585         if(t1 < 10){   
586             if(t1 != 0){   
587                 //一十五 只显示 十五
588                 if(t1!=1){
589                     cn.append(CN[t1]);   
590                 }
591                 cn.append(str);   
592             }else{   
593                 cn.append(CN[0]);   
594             }   
595         }   
596            
597         if(t2 < 10 && t2 != 0){   
598             cn.append(CN[t2]);   
599         }   
600            
601         cn.append("日");      
602           
603         return cn.toString();      
604     } 
605     
606     
607     
608     /** 
609      * 获得本周的第一天,周一 
610      * add by yuxiubao
611      * @return String
612      */ 
613     public String getCurrentWeekDayStartTime() {
614         Calendar c = Calendar.getInstance();
615         try {
616             int weekday = c.get(Calendar.DAY_OF_WEEK) - 2;
617             c.add(Calendar.DATE, -weekday);
618             c.setTime(sf.parse(sf.format(c.getTime())));
619         } catch (Exception e) {
620             e.printStackTrace();
621         }
622         return dateonlysf.format(c.getTime());
623     }
624     /** 
625      * 获得本周的最后一天,周日 
626      * add by yuxiubao
627      * @return String
628      */ 
629     public String getCurrentWeekDayEndTime() {
630         Calendar c = Calendar.getInstance();
631         try {
632             int weekday = c.get(Calendar.DAY_OF_WEEK);
633             c.add(Calendar.DATE, 8 - weekday);
634             c.setTime(sf.parse(sf.format(c.getTime())));
635         } catch (Exception e) {
636             e.printStackTrace();
637         }
638         return dateonlysf.format(c.getTime());
639     }
640     /**
641      * 获得本月的开始日期
642      * add by yuxiubao
643      * @return
644      */
645     public String getCurrentMonthStartTime() {
646         Calendar c = Calendar.getInstance();
647         String resdate = null;
648         try {
649             c.set(Calendar.DATE, 1);
650             resdate = dateonlysf.format(c.getTime());
651         } catch (Exception e) {
652             e.printStackTrace();
653         }
654         return resdate;
655     }
656 
657     /**
658      * 当前月的结束日期
659      * add by yuxiubao
660      * @return
661      */
662     public String getCurrentMonthEndTime() {
663         Calendar c = Calendar.getInstance();
664         String resdate = null;
665         try {
666             c.set(Calendar.DATE, 1);
667             c.add(Calendar.MONTH, 1);
668             c.add(Calendar.DATE, -1);
669             resdate = dateonlysf.format(c.getTime());
670         } catch (Exception e) {
671             e.printStackTrace();
672         }
673         return resdate;
674     } 
675 
676      /** 
677      * 当前季度的开始日期
678      * add by yuxiubao
679      * @return String
680      */ 
681     public String getCurrentQuarterStartTime() {
682         Calendar c = Calendar.getInstance();
683         int currentMonth = c.get(Calendar.MONTH) + 1;
684         String resdate = null;
685         try {
686             if (currentMonth >= 1 && currentMonth <= 3)
687                 c.set(Calendar.MONTH, 0);
688             else if (currentMonth >= 4 && currentMonth <= 6)
689                 c.set(Calendar.MONTH, 3);
690             else if (currentMonth >= 7 && currentMonth <= 9)
691                 c.set(Calendar.MONTH, 4);
692             else if (currentMonth >= 10 && currentMonth <= 12)
693                 c.set(Calendar.MONTH, 9);
694             c.set(Calendar.DATE, 1);
695             resdate = dateonlysf.format(c.getTime());
696         } catch (Exception e) {
697             e.printStackTrace();
698         }
699         return resdate;
700     }
701 
702     /** 
703      * 当前季度的结束日期
704      * add by yuxiubao
705      * @return String
706      */
707     public String getCurrentQuarterEndTime() {
708         Calendar c = Calendar.getInstance();
709         int currentMonth = c.get(Calendar.MONTH) + 1;
710         String resdate = null;
711         try {
712             if (currentMonth >= 1 && currentMonth <= 3) {
713                 c.set(Calendar.MONTH, 2);
714                 c.set(Calendar.DATE, 31);
715             } else if (currentMonth >= 4 && currentMonth <= 6) {
716                 c.set(Calendar.MONTH, 5);
717                 c.set(Calendar.DATE, 30);
718             } else if (currentMonth >= 7 && currentMonth <= 9) {
719                 c.set(Calendar.MONTH, 8);
720                 c.set(Calendar.DATE, 30);
721             } else if (currentMonth >= 10 && currentMonth <= 12) {
722                 c.set(Calendar.MONTH, 11);
723                 c.set(Calendar.DATE, 31);
724             }
725             resdate = dateonlysf.format(c.getTime());
726         } catch (Exception e) {
727             e.printStackTrace();
728         }
729         return resdate;
730     }
731 
732 }

 

日期时间操作的工具类