生活随笔
收集整理的這篇文章主要介紹了
java操作日期的相关工具类,拿去即用
小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
日期工具類(lèi)
1.獲取當(dāng)前Date型日期
2. 獲取當(dāng)前日期, 默認(rèn)格式為yyyy-MM-dd
3. 日期路徑 即年/月/日 如2018/08/08
4. 日期路徑 即年/月/日 如20180808
5. 日期型字符串轉(zhuǎn)化為日期 格式
6. 獲取服務(wù)器啟動(dòng)時(shí)間
7. 計(jì)算兩個(gè)時(shí)間差
8. 兩個(gè)日期相差年或者月 1 :年 , 2 :月
9. 日期相加(日期+年)
10.日期相加(日期+月)
11.特定天數(shù)
12.時(shí)間段是否重疊
13.秒轉(zhuǎn)成時(shí)分秒
14.LocalDate轉(zhuǎn)Date
15. 獲取某區(qū)間段內(nèi)的所有日期
16. 獲取該月的第一天
17. 獲取該月的最后一天
18.獲取時(shí)間段內(nèi)的月份
19.獲取兩個(gè)時(shí)間相差秒數(shù)
20.字符串 轉(zhuǎn) 日期
21.判斷時(shí)間是否在時(shí)間段內(nèi)
22.生成指定年的每一天
23.判斷是否是今年
24.獲取本周第一天和最后一天
25.獲取今天時(shí)間開(kāi)始和結(jié)束
26.獲取本月時(shí)間開(kāi)始和結(jié)束
27.獲取指定日期 幾天前的時(shí)間
28.獲取指定日期的0點(diǎn)和24點(diǎn)
29.獲取30天以前的時(shí)間
30.根據(jù)年月獲取對(duì)應(yīng)的月份天數(shù)
package com.ngs.common.utils;import java.lang.management.ManagementFactory;
import java.sql.Timestamp;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;import org.apache.commons.lang3.time.DateFormatUtils;
public class DateUtils extends org.apache.commons.lang3.time.DateUtils {public static String YYYY
= "yyyy";public static String YYYY_MM
= "yyyy-MM";public static String YYYY_MM_DD
= "yyyy-MM-dd";public static String YYYYMMDDHHMMSS
= "yyyyMMddHHmmss";public static String YYYY_MM_DD_HH_MM_SS
= "yyyy-MM-dd HH:mm:ss";private static String[] parsePatterns
= {"yyyy-MM-dd", "yyyy-MM-dd HH:mm:ss", "yyyy-MM-dd HH:mm", "yyyy-MM","yyyy/MM/dd", "yyyy/MM/dd HH:mm:ss", "yyyy/MM/dd HH:mm", "yyyy/MM","yyyy.MM.dd", "yyyy.MM.dd HH:mm:ss", "yyyy.MM.dd HH:mm", "yyyy.MM"};public static Date getNowDate() {return new Date();}public static String getDate() {return dateTimeNow(YYYY_MM_DD
);}public static final String getTime() {return dateTimeNow(YYYY_MM_DD_HH_MM_SS
);}public static final String dateTimeNow() {return dateTimeNow(YYYYMMDDHHMMSS
);}public static final String dateTimeNow(final String format
) {return parseDateToStr(format
, new Date());}public static final String dateTime(final Date date
) {return parseDateToStr(YYYY_MM_DD
, date
);}public static final String parseDateToStr(final String format
, final Date date
) {return new SimpleDateFormat(format
).format(date
);}public static final Date dateTime(final String format
, final String ts
) {try {return new SimpleDateFormat(format
).parse(ts
);} catch (ParseException e
) {throw new RuntimeException(e
);}}public static final String datePath() {Date now
= new Date();return DateFormatUtils.format(now
, "yyyy/MM/dd");}public static final String dateTime() {Date now
= new Date();return DateFormatUtils.format(now
, "yyyyMMdd");}public static Date parseDate(Object str
) {if (str
== null) {return null;}try {return parseDate(str
.toString(), parsePatterns
);} catch (ParseException e
) {return null;}}public static Date getServerStartDate() {long time
= ManagementFactory.getRuntimeMXBean().getStartTime();return new Date(time
);}public static String getDatePoor(Date endDate
, Date nowDate
) {long nd
= 1000 * 24 * 60 * 60;long nh
= 1000 * 60 * 60;long nm
= 1000 * 60;long diff
= endDate
.getTime() - nowDate
.getTime();long day
= diff
/ nd
;long hour
= diff
% nd
/ nh
;long min
= diff
% nd
% nh
/ nm
;return day
+ "天" + hour
+ "小時(shí)" + min
+ "分鐘";}public static int getMonthNum(String date1
, String date2
, int type
) throws java.text.ParseException {int result
= 0;SimpleDateFormat sdf
= new SimpleDateFormat(type
== 1 ? "yyyy" : "yyyy-MM");Calendar c1
= Calendar.getInstance();Calendar c2
= Calendar.getInstance();c1
.setTime(sdf
.parse(date1
));c2
.setTime(sdf
.parse(date2
));if (type
== 1) {result
= c2
.get(Calendar.YEAR
) - c1
.get(Calendar.YEAR
);System.out
.println("日期:" + date1
+ "|" + date2
+ "|,相差" + Math.abs(result
) + "年");return result
;} else {result
= c2
.get(Calendar.MONTH
) - c1
.get(Calendar.MONTH
);int month
= (c2
.get(Calendar.YEAR
) - c1
.get(Calendar.YEAR
)) * 12;log
.info("|到期時(shí)間:" + date2
+ "減去現(xiàn)在日期:" + date1
+ "|,剩余" + (month
+ result
) + "個(gè)月");return month
+ result
;}}public String addDate(String date
, int year
) throws ParseException {SimpleDateFormat sdFormat
= new SimpleDateFormat("yyyy-MM-dd");Calendar calendar
= Calendar.getInstance();calendar
.setTime(sdFormat
.parse(date
));calendar
.add(Calendar.YEAR
, year
);String format
= sdFormat
.format(calendar
.getTime());return format
;}public String addDate(String date
, int mouth
) throws ParseException {SimpleDateFormat sdFormat
= new SimpleDateFormat("yyyy-MM-dd");Calendar calendar
= Calendar.getInstance();calendar
.setTime(sdFormat
.parse(date
));calendar
.add(Calendar.MOUTH
, mouth
);String format
= sdFormat
.format(calendar
.getTime());return format
;}public static long getDays(String str
, String endt
) throws Exception {SimpleDateFormat simpleDateFormat
= new SimpleDateFormat("yyyy-MM-dd");Date strD
= simpleDateFormat
.parse(str
);Date endtD
= simpleDateFormat
.parse(endt
);long day
= endtD
.getTime() - strD
.getTime();long l
= day
/ (24 * 3600 * 1000);return l
;}public static boolean isOverlap(List<Date> startList
, List<Date> endList
) throws ParseException {List<Timestamp> periodStart
= new ArrayList<Timestamp>();List<Timestamp> periodend
= new ArrayList<Timestamp>();SimpleDateFormat sdf
= new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");startList
.stream().forEach(x
-> {periodStart
.add(new Timestamp(x
.getTime()));});endList
.stream().forEach(x
-> {periodend
.add(new Timestamp(x
.getTime()));});for (int i
= 0; i
< periodStart
.size() - 1; i
++) {Timestamp start0
= periodStart
.get(i
);Timestamp end0
= periodend
.get(i
);for (int j
= i
+ 1; j
< periodStart
.size(); j
++) {Timestamp start
= periodStart
.get(j
);Timestamp end
= periodend
.get(j
);if (start0
.compareTo(end
) >= 0 || end0
.compareTo(start
) <= 0) {continue;} else {return true;}}}return false;}public static String getFormatTime(Long second
) {if (second
!= null) {String num0
= NumFormat(0);if (second
< 60) {return num0
+ ":" + num0
+ ":" + NumFormat(second
);}if (second
< 3600) {return num0
+ ":" + NumFormat(second
/ 60) + ":" + NumFormat(second
% 60);}if (second
< 3600 * 24) {return NumFormat(second
/ 60 / 60) + ":" + NumFormat(second
/ 60 % 60) + ":" + NumFormat(second
% 60);}if (second
>= 3600 * 24) {return NumFormat(second
/ 60 / 60 / 24) + "天" + NumFormat(second
/ 60 / 60 % 24) + ":" + NumFormat(second
/ 60 % 60) + ":" + NumFormat(second
% 60);}}return "--";}public static Date LocalDate2Date(LocalDate localDate
) {ZonedDateTime zonedDateTime
= localDate
.atStartOfDay(ZoneId.systemDefault());return Date.from(zonedDateTime
.toInstant());}public static List<String> findDates(Date startTime
, Date endTime
) throws Exception {SimpleDateFormat sdf
= new SimpleDateFormat("yyyy-MM-dd");List<String> result
= new ArrayList<>();Calendar calBegin
= Calendar.getInstance();calBegin
.setTime(startTime
);Calendar calEnd
= Calendar.getInstance();calEnd
.setTime(endTime
);while (endTime
.after(calBegin
.getTime())) {result
.add(sdf
.format(calBegin
.getTime()));calBegin
.add(Calendar.DAY_OF_MONTH
, 1);}result
.add(sdf
.format(calEnd
.getTime()));return result
;}public static Date getFirstDay(int year
, int month
) {Calendar c
= Calendar.getInstance();c
.set(Calendar.YEAR
, year
);c
.set(Calendar.MONTH
, month
- 1);c
.set(Calendar.DAY_OF_MONTH
, 1);Date time
= c
.getTime();SimpleDateFormat slf
= new SimpleDateFormat("yyyy-MM-dd");String format
= slf
.format(time
);try {return slf
.parse(format
);} catch (ParseException e
) {e
.printStackTrace();}return null;}public static Date getLastDay
( int year
, int month
){Calendar c
= Calendar.getInstance();c
.set(Calendar.YEAR
, year
);c
.set(Calendar.MONTH
, month
- 1);int lastDay
= c
.getActualMaximum(Calendar.DAY_OF_MONTH
);c
.set(Calendar.DAY_OF_MONTH
, lastDay
);Date time
= c
.getTime();SimpleDateFormat slf
= new SimpleDateFormat("yyyy-MM-dd");String format
= slf
.format(time
);try {return slf
.parse(format
);} catch (ParseException e
) {e
.printStackTrace();}return null;}public static List<String> getMonthBetween(String minDate
, String maxDate
){ArrayList<String> result
= new ArrayList<>();try {SimpleDateFormat sdf
= new SimpleDateFormat("yyyy-MM");Calendar min
= Calendar.getInstance();Calendar max
= Calendar.getInstance();min
.setTime(sdf
.parse(minDate
));min
.set(min
.get(Calendar.YEAR
), min
.get(Calendar.MONTH
), 1);max
.setTime(sdf
.parse(maxDate
));max
.set(max
.get(Calendar.YEAR
), max
.get(Calendar.MONTH
), 2);while (min
.before(max
)) {result
.add(sdf
.format(min
.getTime()));min
.add(Calendar.MONTH
, 1);}} catch (ParseException e
) {e
.printStackTrace();}return result
;}public static long getTimeDelta(Date startDate
,Date endDate
) {long a
= endDate
.getTime();long b
= startDate
.getTime();long c
=((a
- b
) / 1000);return c
;}public static Date strToDate(String str
) {SimpleDateFormat sdf
= new SimpleDateFormat("yyyy-MM-dd");Date date
= null;try {date
= sdf
.parse(str
);} catch (ParseException e
) {}return date
;}public static boolean belongCalendar(Date nowTime
, Date beginTime
, Date endTime
) {Calendar date
= Calendar.getInstance();date
.setTime(nowTime
);Calendar begin
= Calendar.getInstance();begin
.setTime(beginTime
);Calendar end
= Calendar.getInstance();end
.setTime(endTime
);if (date
.after(begin
) && date
.before(end
)) {return true;} else if (nowTime
.compareTo(beginTime
) == 0 ) {return true;} else {return false;}}public static List<String> getDaysByYear(int year
){Calendar c
=Calendar.getInstance();List<String> dates
=new ArrayList<String>();for(int i
=0;i
<12;i
++){c
.set(year
,i
,1);int lastDay
=c
.getActualMaximum(Calendar.DATE
);for(int j
=1;j
<=lastDay
;j
++){String month
="";String day
="";if(i
<9) month
="-0"+(i
+1);else month
="-"+(i
+1);if(j
<10) day
="-0"+j
;else day
="-"+j
;String date
=year
+month
+day
;dates
.add(date
);}}return dates
;}public static boolean isNowYear(int year
){Calendar date
= Calendar.getInstance();String years
= String.valueOf(date
.get(Calendar.YEAR
));return years
.equals(year
+ "");}public static String beforeDate(int day
) {Calendar now
= Calendar.getInstance();now
.add(Calendar.DAY_OF_MONTH
, -day
);String endDate
= new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(now
.getTime());return endDate
;}private static String NumFormat(long sec
) {if (String.valueOf(sec
).length() < 2) {return "0" + sec
;} else {return String.valueOf(sec
);}}private static String yearLast() {String yearLast
= new SimpleDateFormat("yy", Locale.CHINESE
).format(Calendar.getInstance().getTime());return yearLast
;}public static String mixTimeStr(String endTime
) {Calendar rCalendar
= Calendar.getInstance();SimpleDateFormat simpleDateFormat
= new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");Date date
= null;try {date
= simpleDateFormat
.parse(endTime
);} catch (Exception e
) {e
.printStackTrace();}rCalendar
.setTime(date
);rCalendar
.add(Calendar.HOUR
, 23);rCalendar
.add(Calendar.MINUTE
, 59);rCalendar
.add(Calendar.SECOND
, 59);return simpleDateFormat
.format(rCalendar
.getTime());}public static String getWeekStart(){Calendar cal
=Calendar.getInstance();cal
.add(Calendar.WEEK_OF_MONTH
, 0);cal
.set(Calendar.DAY_OF_WEEK
, 2);Date time
=cal
.getTime();return new SimpleDateFormat("yyyy-MM-dd").format(time
)+" 00:00:00";}public static String getWeekEnd(){Calendar cal
=Calendar.getInstance();cal
.set(Calendar.DAY_OF_WEEK
, cal
.getActualMaximum(Calendar.DAY_OF_WEEK
));cal
.add(Calendar.DAY_OF_WEEK
, 1);Date time
=cal
.getTime();return new SimpleDateFormat("yyyy-MM-dd").format(time
)+" 23:59:59";}public static Date getStartTime() {Calendar todayStart
= Calendar.getInstance();todayStart
.set(Calendar.HOUR
, 0);todayStart
.set(Calendar.MINUTE
, 0);todayStart
.set(Calendar.SECOND
, 0);todayStart
.set(Calendar.MILLISECOND
, 0);return todayStart
.getTime();}public static Date getEndTime() {Calendar todayEnd
= Calendar.getInstance();todayEnd
.set(Calendar.HOUR
, 23);todayEnd
.set(Calendar.MINUTE
, 59);todayEnd
.set(Calendar.SECOND
, 59);todayEnd
.set(Calendar.MILLISECOND
, 999);return todayEnd
.getTime();}public static Date getTimesMonthmorning() {Calendar cal
= Calendar.getInstance();cal
.set(cal
.get(Calendar.YEAR
), cal
.get(Calendar.MONDAY
), cal
.get(Calendar.DAY_OF_MONTH
), 0, 0, 0);cal
.set(Calendar.DAY_OF_MONTH
, cal
.getActualMinimum(Calendar.DAY_OF_MONTH
));return cal
.getTime();}public static Date getTimesMonthnight() {Calendar cal
= Calendar.getInstance();cal
.set(cal
.get(Calendar.YEAR
), cal
.get(Calendar.MONDAY
), cal
.get(Calendar.DAY_OF_MONTH
), 0, 0, 0);cal
.set(Calendar.DAY_OF_MONTH
, cal
.getActualMaximum(Calendar.DAY_OF_MONTH
));cal
.set(Calendar.HOUR_OF_DAY
, 24);return cal
.getTime();}
public Date getDateAfter(Date d
, int day
) {SimpleDateFormat format
= new SimpleDateFormat("yyyy-MM-dd");Calendar now
= Calendar.getInstance();now
.setTime(d
);now
.set(Calendar.DATE
, now
.get(Calendar.DATE
) - day
);return now
.getTime();}public static String getStartOfDay(Date time
) {Calendar calendar
= Calendar.getInstance();calendar
.setTime(time
);calendar
.set(Calendar.HOUR_OF_DAY
, 0);calendar
.set(Calendar.MINUTE
, 0);calendar
.set(Calendar.SECOND
, 0);calendar
.set(Calendar.MILLISECOND
, 0);return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(calendar
.getTime());}public static String getEndOfDay(Date time
) {Calendar calendar
= Calendar.getInstance();calendar
.setTime(time
);calendar
.set(Calendar.HOUR_OF_DAY
, 23);calendar
.set(Calendar.MINUTE
, 59);calendar
.set(Calendar.SECOND
, 59);calendar
.set(Calendar.MILLISECOND
, 999);return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(calendar
.getTime());}public static String getThirtyDaysAgo(Date time
) {Calendar calendar
= Calendar.getInstance();calendar
.setTime(time
);calendar
.add(calendar
.DATE
, -30);calendar
.set(Calendar.HOUR_OF_DAY
, 0);calendar
.set(Calendar.MINUTE
, 0);calendar
.set(Calendar.SECOND
, 0);calendar
.set(Calendar.MILLISECOND
, 0);return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(calendar
.getTime());}public static int getDaysByYearMonth(int year
, int month
) {
Calendar a
= Calendar.getInstance();a
.set(Calendar.YEAR
, year
);a
.set(Calendar.MONTH
, month
- 1);a
.set(Calendar.DATE
, 1);a
.roll(Calendar.DATE
, -1);int maxDate
= a
.get(Calendar.DATE
);return maxDate
;}}
總結(jié)
以上是生活随笔為你收集整理的java操作日期的相关工具类,拿去即用的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
如果覺(jué)得生活随笔網(wǎng)站內(nèi)容還不錯(cuò),歡迎將生活随笔推薦給好友。