Java 时间工具类

  1 /**
  2      * 格式化字符串为日期格式
  3      *
  4      * @param dateStr 需要格式化的字符串
  5      * @param format  需要的日期格式,例如"yyyy-MM-dd HH:mm:ss"
  6      * @return
  7      */
  8     public static Date formatDate(String dateStr, String format) {
  9         SimpleDateFormat dateFormat = new SimpleDateFormat(format,
 10                 Locale.CHINESE);
 11         try {
 12             return dateFormat.parse(dateStr);
 13         } catch (ParseException e) {
 14             e.printStackTrace();
 15         }
 16 
 17         return null;
 18     }
 19 
 20     /**
 21      * 格式化字符串为"yyyy-MM-dd HH:mm:ss"的日期
 22      *
 23      * @param dateStr
 24      * @return
 25      */
 26     public static Date formatDate(String dateStr) {
 27         if(StrUtil.isBlank(dateStr)){
 28             return null;
 29         }
 30         return formatDate(dateStr, "yyyy-MM-dd HH:mm:ss");
 31     }
 32 
 33     public static String getFormatDateStr(long date, String format) {
 34         return formatDate2Str(new Date(date), format);
 35     }
 36 
 37     public static String getMonthDayStr(Date date) {
 38         if (date == null) {
 39             return "";
 40         }
 41         return formatDate2Str(date, "MM-dd");
 42     }
 43 
 44     public static String getNormalDateStr(Date date) {
 45         if (date == null) {
 46             return "";
 47         }
 48         return formatDate2Str(date, "yyyy-MM-dd HH:mm:ss");
 49     }
 50 
 51     public static String formatDate2Str(Date date, String formatter) {
 52         SimpleDateFormat sdf = new SimpleDateFormat(formatter);
 53         return sdf.format(date);
 54     }
 55 
 56     /**
 57      * date 日期加上,或减去几天
 58      *
 59      * @param date
 60      * @param day
 61      * @return
 62      */
 63     public static Date addDateInDiff(Date date, int day) {
 64         Calendar cal = Calendar.getInstance();
 65         cal.setTime(date);
 66         cal.add(Calendar.DATE, day);
 67         return cal.getTime();
 68     }
 69 
 70     public static Date addMinuteInDiff(Date date, int minute) {
 71         Calendar cal = Calendar.getInstance();
 72         cal.setTime(date);
 73         cal.add(Calendar.MINUTE, minute);
 74         return cal.getTime();
 75     }
 76 
 77     public static Date addSecondInDiff(Date date, int sec) {
 78         Calendar cal = Calendar.getInstance();
 79         cal.setTime(date);
 80         cal.add(Calendar.SECOND, sec);
 81         return cal.getTime();
 82     }
 83 
 84     /**
 85      * 日期加个月
 86      *
 87      * @param date
 88      * @param mon
 89      * @return
 90      */
 91     public static Date addMonthInDiff(Date date, int mon) {
 92         Calendar cal = Calendar.getInstance();
 93         cal.setTime(date);
 94         cal.add(Calendar.MONTH, mon);
 95         return cal.getTime();
 96     }
 97 
 98     public static Date addYearInDiff(Date date, int mon) {
 99         Calendar cal = Calendar.getInstance();
100         cal.setTime(date);
101         cal.add(Calendar.YEAR, mon);
102         return cal.getTime();
103     }
104 
105     /**
106      * 获取当前日期是星期几<br>
107      *
108      * @param dt
109      * @return 当前日期是星期几
110      */
111     public static String getWeekOfDate(Date dt) {
112         String[] weekDays = {"星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六"};
113         Calendar cal = Calendar.getInstance();
114         cal.setTime(dt);
115         int w = cal.get(Calendar.DAY_OF_WEEK) - 1;
116         if (w < 0)
117             w = 0;
118         return weekDays[w];
119     }
120 
121     /**
122      * 获取当前日期是周几<br>
123      *
124      * @param dt
125      * @return 当前日期是周几
126      */
127     public static String getWeekOfDate2(Date dt) {
128         String[] weekDays = {"周日", "周一", "周二", "周三", "周四", "周五", "周六"};
129         Calendar cal = Calendar.getInstance();
130         cal.setTime(dt);
131         int w = cal.get(Calendar.DAY_OF_WEEK) - 1;
132         if (w < 0)
133             w = 0;
134         return weekDays[w];
135     }
136 
137     /**
138      * <pre>
139      * 判断date和当前日期是否在同一周内
140      * 注:
141      * Calendar类提供了一个获取日期在所属年份中是第几周的方法,对于上一年末的某一天
142      * 和新年初的某一天在同一周内也一样可以处理,例如2012-12-31和2013-01-01虽然在
143      * 不同的年份中,但是使用此方法依然判断二者属于同一周内
144      * </pre>
145      *
146      * @param date
147      * @return
148      */
149     public static boolean isSameWeekWithToday(Date date) {
150         return isSameWeek(date, new Date());
151     }
152 
153     public static boolean isSameWeek(Date date1, Date date2) {
154         if (date1 == null || date2 == null) {
155             return false;
156         }
157 
158         // 0.先把Date类型的对象转换Calendar类型的对象
159         Calendar date1Cal = Calendar.getInstance();
160         Calendar date2Cal = Calendar.getInstance();
161 
162         date1Cal.setTime(date1);
163         date2Cal.setTime(date2);
164 
165         // 1.比较当前日期在年份中的周数是否相同
166         if (date1Cal.get(Calendar.WEEK_OF_YEAR) == date2Cal
167                 .get(Calendar.WEEK_OF_YEAR)) {
168             return true;
169         } else {
170             return false;
171         }
172     }
173 
174     /**
175      * 取得当前日期所在周的第一天
176      *
177      * @param date
178      * @return
179      */
180     public static Date getFirstDayOfWeek(Date date) {
181         Calendar c = new GregorianCalendar();
182         c.setFirstDayOfWeek(Calendar.MONDAY);
183         c.setTime(date);
184         c.set(Calendar.DAY_OF_WEEK, c.getFirstDayOfWeek()); // Monday
185         return c.getTime();
186     }
187 
188     /**
189      * 取得当前日期是多少周
190      *
191      * @param date
192      * @return
193      */
194     public static int getWeekOfYear(Date date) {
195         Calendar c = new GregorianCalendar();
196         c.setFirstDayOfWeek(Calendar.MONDAY);
197         c.setMinimalDaysInFirstWeek(7);
198         c.setTime(date);
199 
200         return c.get(Calendar.WEEK_OF_YEAR);
201     }
202 
203     /**
204      * 得到某一年周的总数
205      *
206      * @param year
207      * @return
208      */
209     public static int getMaxWeekNumOfYear(int year) {
210         Calendar c = new GregorianCalendar();
211         c.set(year, Calendar.DECEMBER, 31, 23, 59, 59);
212 
213         return getWeekOfYear(c.getTime());
214     }
215 
216     /**
217      * 得到某年某周的第一天
218      *
219      * @param year
220      * @param week
221      * @return
222      */
223     public static Date getFirstDayOfWeek(int year, int week) {
224         Calendar c = new GregorianCalendar();
225         c.set(Calendar.YEAR, year);
226         c.set(Calendar.MONTH, Calendar.JANUARY);
227         c.set(Calendar.DATE, 1);
228 
229         Calendar cal = (GregorianCalendar) c.clone();
230         cal.add(Calendar.DATE, week * 7);
231 
232         return getFirstDayOfWeek(cal.getTime());
233     }
234 
235     /**
236      * 得到某年某周的最后一天
237      *
238      * @param year
239      * @param week
240      * @return
241      */
242     public static Date getLastDayOfWeek(int year, int week) {
243         Calendar c = new GregorianCalendar();
244         c.set(Calendar.YEAR, year);
245         c.set(Calendar.MONTH, Calendar.JANUARY);
246         c.set(Calendar.DATE, 1);
247 
248         Calendar cal = (GregorianCalendar) c.clone();
249         cal.add(Calendar.DATE, week * 7);
250 
251         return getLastDayOfWeek(cal.getTime());
252     }
253 
254     /**
255      * 取得当前日期所在周的最后一天
256      *
257      * @param date
258      * @return
259      */
260     public static Date getLastDayOfWeek(Date date) {
261         Calendar c = new GregorianCalendar();
262         c.setFirstDayOfWeek(Calendar.MONDAY);
263         c.setTime(date);
264         c.set(Calendar.DAY_OF_WEEK, c.getFirstDayOfWeek() + 6); // Sunday
265         return c.getTime();
266     }
267 
268     /**
269      * 获得当前日期所在月份的最后一天(最后一个day)
270      *
271      * @param date
272      * @return Date
273      */
274     public static Date getLastDayOfMonth(Date date) {
275         Calendar ca = Calendar.getInstance();
276         ca.setTime(date);
277         ca.set(Calendar.DAY_OF_MONTH,
278                 ca.getActualMaximum(Calendar.DAY_OF_MONTH));
279         return ca.getTime();
280     }
281 
282     public static Date getFirstDayOfMonth(Date date) {
283         Calendar c = Calendar.getInstance();
284         c.add(Calendar.MONTH, 0);
285         c.set(Calendar.DAY_OF_MONTH, 1);// 设置为1号,当前日期既为本月第一天
286         return c.getTime();
287     }
288 
289     /**
290      * 获取两个日期之间的天数
291      *
292      * @param startDate
293      * @param endDate
294      * @return
295      */
296     public static Long getDaysBetween(Date startDate, Date endDate) {
297         Calendar fromCalendar = Calendar.getInstance();
298         fromCalendar.setTime(startDate);
299         fromCalendar.set(Calendar.HOUR_OF_DAY, 0);
300         fromCalendar.set(Calendar.MINUTE, 0);
301         fromCalendar.set(Calendar.SECOND, 0);
302         fromCalendar.set(Calendar.MILLISECOND, 0);
303 
304         Calendar toCalendar = Calendar.getInstance();
305         toCalendar.setTime(endDate);
306         toCalendar.set(Calendar.HOUR_OF_DAY, 0);
307         toCalendar.set(Calendar.MINUTE, 0);
308         toCalendar.set(Calendar.SECOND, 0);
309         toCalendar.set(Calendar.MILLISECOND, 0);
310 
311         return (toCalendar.getTime().getTime() - fromCalendar.getTime()
312                 .getTime()) / (1000 * 60 * 60 * 24);
313     }
314 
315     /**
316      * 计算两个分钟差
317      *
318      * @return
319      */
320     public static Long getMinutesBetween(Date startDate, Date endDate) {
321         long diff = startDate.getTime() - endDate.getTime();//这样得到的差值是微秒级别
322         long days = diff / (1000 * 60 * 60 * 24);
323 
324         long hours = (diff - days * (1000 * 60 * 60 * 24)) / (1000 * 60 * 60);
325         long minutes = diff / (1000 * 60);
326         System.out.println("" + days + "天" + hours + "小时" + minutes + "分");
327         return minutes;
328     }
329 
330     /**
331      * 计算两个小时差
332      *
333      * @return
334      */
335     public static Long getHourBetween(Date startDate, Date endDate) {
336         long diff = startDate.getTime() - endDate.getTime();//这样得到的差值是微秒级别
337         long days = diff / (1000 * 60 * 60 * 24);
338 
339         long hours = diff / (1000 * 60 * 60);
340         System.out.println("" + days + "天" + hours + "小时" + "分");
341         return hours;
342     }
343 
344     /**
345      * 计算两个秒差
346      *
347      * @return
348      */
349     public static Long getSecondBetween(Date startDate, Date endDate) {
350         long diff = startDate.getTime() - endDate.getTime();//这样得到的差值是微秒级别
351         long seconds = diff / (1000);
352         return seconds;
353     }
354 
355     /**
356      * 日期转换为今天,明天,后天
357      * startDate (2018-09-10 00:00:00)
358      */
359     public static String getDateDesc(Date startDate) {
360         String todayStr = formatDate2Str(new Date(), "yyyy-MM-dd");
361         Date today = formatDate(todayStr + " 00:00:00");
362         long days = getDaysBetween(today, startDate);
363         if (days == 0) {
364             return "今天";
365         } else if (days == 1) {
366             return "明天";
367         } else if (days == 2) {
368             return "后天";
369         }
370         return formatDate2Str(startDate, "yyyy-MM-dd");
371     }
372 
373     /**
374      * 显示时间,如果与当前时间差别小于一天,则自动用**秒(分,小时)前,如果大于一天则用format规定的格式显示
375      *
376      * @param ctime  时间
377      * @param format 格式 格式描述:例如:yyyy-MM-dd yyyy-MM-dd HH:mm:ss
378      * @return
379      */
380     public static String showTime(Date ctime, String format) {
381         // System.out.println("当前时间是:"+new
382         // Timestamp(System.currentTimeMillis()));
383 
384         // System.out.println("发布时间是:"+df.format(ctime).toString());
385         String r = "";
386         if (ctime == null)
387             return r;
388         if (format == null)
389             format = "MM-dd HH:mm";
390 
391         boolean isSameYear = isSameYear(ctime, new Date());
392         if (!isSameYear) {
393             format = "yy-M-d";
394             SimpleDateFormat df = new SimpleDateFormat(format);
395             return df.format(ctime);
396         }
397 
398         long nowtimelong = System.currentTimeMillis();
399 
400         long ctimelong = ctime.getTime();
401         long result = Math.abs(nowtimelong - ctimelong);
402 
403         if (result < 60000) {// 一分钟内
404             // long seconds = result / 1000;
405             // if(seconds == 0){
406             // r = "刚刚";
407             // }else{
408             // r = seconds + "秒前";
409             // }
410             r = "刚刚";
411         } else if (result >= 60000 && result < 3600000) {// 一小时内
412             long seconds = result / 60000;
413             r = seconds + "分钟前";
414         } else if (result >= 3600000 && result < 86400000) {// 一天内
415             long seconds = result / 3600000;
416             r = seconds + "小时前";
417         } else if (result > 86400000 && result < 172800000) {// 三十天内
418             // long seconds = result / 86400000;
419             // r = seconds + "天前";
420             r = "昨天";
421         } else if (result >= 172800000) {
422 //            format = "M-d";
423             SimpleDateFormat df = new SimpleDateFormat(format);
424             r = df.format(ctime).toString();
425         }
426         // else{// 日期格式
427         // format="MM-dd HH:mm";
428         // SimpleDateFormat df = new SimpleDateFormat(format);
429         // r = df.format(ctime).toString();
430         // }
431         return r;
432     }
433 
434     public static boolean isSameYear(Date ctime, Date nTime) {
435         Calendar cDate = Calendar.getInstance();
436         cDate.setTime(ctime);
437         Calendar nDate = Calendar.getInstance();
438         nDate.setTime(nTime);
439         int cYear = cDate.get(Calendar.YEAR);
440         int nYear = nDate.get(Calendar.YEAR);
441         if (cYear == nYear) {
442             return true;
443         }
444         return false;
445     }
446 
447     /***
448      * 出生日期转换年龄
449      ***/
450     public static int getAgeByBirthday(Date birthday) {
451         Calendar cal = Calendar.getInstance();
452         if (birthday.getTime() > new Date().getTime()) {
453             return 0;
454         }
455         int year = cal.get(Calendar.YEAR);
456         int month = cal.get(Calendar.MONTH) + 1;
457         int day = cal.get(Calendar.DAY_OF_MONTH);
458 
459         cal.setTime(birthday);
460         int yearBirth = cal.get(Calendar.YEAR);
461         int monthBirth = cal.get(Calendar.MONTH) + 1;
462         int dayBirth = cal.get(Calendar.DAY_OF_MONTH);
463         int age = year - yearBirth;
464         if (monthBirth > month)
465             return age - 1;
466         if (monthBirth == month && dayBirth > day)
467             return age - 1;
468         return age > 0 ? age : 0;
469     }
470 
471     /***
472      * 根据年龄取得出生日期
473      *
474      * @param age
475      * @return
476      */
477     public static String getBirthdayByAge(int age) {
478         Calendar cal = Calendar.getInstance();
479         int year = cal.get(Calendar.YEAR);
480         int month = cal.get(Calendar.MONTH) + 1;
481         int day = cal.get(Calendar.DAY_OF_MONTH);
482         int birthYear = year - age;
483         Date birthDay = formatDate(birthYear + "-" + month + "-" + day,
484                 "yyyy-MM-dd");
485         return formatDate2Str(birthDay, "yyyy-MM-dd");
486     }
487 
488 
489     /**
490      * 判断结束时间是否早于当前时间
491      **/
492     public static boolean isTimeout(String date) {
493         if (date == null)
494             return false;
495         long now = new Date().getTime();
496         long end = formatDate(date.toString()).getTime();
497         if (now > end)
498             return true;
499         return false;
500     }
501 
502     /**
503      * @param date
504      * @return
505      */
506     public static boolean isTimeout(Date date) {
507         if (date == null) return false;
508         long now = new Date().getTime();
509         long end = date.getTime();
510         if (now > end) return true;
511         return false;
512     }
513 
514     /**
515      * 判断date2时间是否早于date1时间
516      **/
517     public static boolean isTimeout(String date1, String date2) {
518         if (date1 == null || date2 == null)
519             return false;
520         long start = formatDate(date2.toString()).getTime();
521         long end = formatDate(date1.toString()).getTime();
522         if (start > end)
523             return true;
524         return false;
525     }
526 
527     /**
528      * 判断传入的时间是否已满一周年
529      */
530     public static boolean isLastYear(Date date) {
531         Calendar calendar = Calendar.getInstance();
532         Date lastYear = new Date(System.currentTimeMillis());
533         calendar.setTime(lastYear);
534         calendar.add(Calendar.YEAR, -1);
535         lastYear = calendar.getTime();
536         if (date.getTime() < lastYear.getTime()) {
537             return true;
538         }
539         return false;
540     }
541 
542     public static int getSpecVoteFailTime() {
543         Date nowDate = new Date();
544         Date addDateInDiff = addDateInDiff(nowDate, 1);
545         String endDateStr = formatDate2Str(addDateInDiff, "yyyy-MM-dd") + " 00:00:00";
546         Date formatDate = formatDate(endDateStr);
547         long time1 = formatDate.getTime();
548         long time2 = nowDate.getTime();
549         long abs = Math.abs(time1 - time2);
550         long l = abs / 1000;
551         return Integer.valueOf(String.valueOf(l));
552     }
553 
554     //2018-09-17 9时 转成日期格式
555     public static String convertShowTimeToDate(String date) {
556         StringBuilder str = new StringBuilder();
557         str.append(date);
558         if (date.length() == 13) {
559             str.insert(11, 0);
560         }
561         date = date.replace("时", ":00:00");
562         System.out.println(date);
563         return date;
564     }
565 
566     //日期格式转成2018-09-17 9时
567     public static String convertDateToShowTime(Date date) {
568         String dateStr = UtilDate.formatDate2Str(date, "yyyy-MM-dd HH");
569         String regx = "\\s0";
570         dateStr = dateStr.replaceAll(regx, " ") + "时";
571         System.out.println(dateStr);
572         return dateStr;
573     }
574 
575 
576     /**
577      * 第几个工作日
578      *
579      * @param date
580      * @param days
581      * @return
582      */
583     public static Date getWorkDte(Date date, int days) {
584 
585         Calendar calendar = Calendar.getInstance();
586         calendar.setTime(date);
587         if (days > 0) {
588             for (int i = 1; i <= days; i++) {
589                 calendar.add(Calendar.DAY_OF_YEAR, 1);
590                 if (calendar.get(Calendar.DAY_OF_WEEK) == Calendar.SATURDAY || calendar.get(Calendar.DAY_OF_WEEK) == Calendar.SUNDAY) {
591                     i--;
592                 }
593             }
594         } else if (days < 0) {
595             for (int i = 0; i > days; i--) {
596                 calendar.add(Calendar.DAY_OF_YEAR, -1);
597                 if (calendar.get(Calendar.DAY_OF_WEEK) == Calendar.SATURDAY || calendar.get(Calendar.DAY_OF_WEEK) == Calendar.SUNDAY) {
598                     i++;
599                 }
600             }
601         }
602         return calendar.getTime();
603     }
604 
605     /**
606      * 几小时几分钟
607      *
608      * @param seconds
609      * @return
610      */
611     public static String getTimeStrBySeconds(int seconds) {
612         String timeStr = "";
613         int hour = seconds / (60 * 60);
614         int minute = seconds % (60 * 60) / 60;
615         if (0 == hour) {
616             timeStr = seconds % (60 * 60) / 60 + "分钟";
617 
618         } else {
619             timeStr = seconds / (60 * 60) + "小时" + seconds % (60 * 60) / 60 + "分钟";
620 
621         }
622         return timeStr;
623     }
624 
625     //判断选择的日期是否是本周
626     public static boolean isThisWeek(long time)
627     {
628         Calendar calendar = Calendar.getInstance();
629         int currentWeek = calendar.get(Calendar.WEEK_OF_YEAR);
630         calendar.setTime(new Date(time));
631         int paramWeek = calendar.get(Calendar.WEEK_OF_YEAR);
632         if(paramWeek==currentWeek){
633             return true;
634         }
635         return false;
636     }
637     //判断选择的日期是否是今天
638     public static boolean isToday(long time)
639     {
640         return isThisTime(time,"yyyy-MM-dd");
641     }
642     //判断选择的日期是否是本月
643     public static boolean isThisMonth(long time)
644     {
645         return isThisTime(time,"yyyy-MM");
646     }
647     private static boolean isThisTime(long time,String pattern) {
648         Date date = new Date(time);
649         SimpleDateFormat sdf = new SimpleDateFormat(pattern);
650         String param = sdf.format(date);//参数时间
651         String now = sdf.format(new Date());//当前时间
652         if(param.equals(now)){
653             return true;
654         }
655         return false;
656     }
657 
658     /**
659      * 当天时间获取时分
660      * @return
661      */
662     public static String getIsTodayStartTime(Date date){
663 //        Date date = UtilDate.formatDate(time, "yyyy-MM-dd HH:mm");
664         long time1 = date.getTime();
665         boolean today = UtilDate.isToday(time1);
666         String todayTime = UtilDate.getFormatDateStr(date.getTime(),"yyyy-MM-dd HH:mm");
667         if (today){
668 
669             String regex = " ";
670             String[] split = todayTime.split(regex);
671             return "今天 " + split[1];
672         }
673         return todayTime;
674     }
675 
676     /**
677      * 当天时间获取时分
678      * @return
679      */
680     public static String getIsTodayEndTime(Date date){
681 //        Date date = UtilDate.formatDate(time, "yyyy-MM-dd HH:mm");
682         long time1 = date.getTime();
683         boolean today = UtilDate.isToday(time1);
684         String todayTime = UtilDate.getFormatDateStr(date.getTime(),"yyyy-MM-dd HH:mm");
685         if (today){
686             String regex = " ";
687             String[] split = todayTime.split(regex);
688             return split[1];
689         }
690         return todayTime.substring(11);
691     }

 

posted on 2019-06-04 17:41  你猜怎么着  阅读(479)  评论(0编辑  收藏  举报

导航