java日期处理工具类
本文针对日期处理进行学习使用,主要分为两部分,下面为大家具体介绍一下
第一部分:日期处理基础知识
Date类
作用:最主要的作用就是获得当前时间
将日期转换为标准格式
Datedate=newDate(); SimpleDateFormatsdf=newSimpleDateFormat("yyyy-MM-ddHH:mm:ss"); Stringstr=sdf.format(date); System.out.println(“2015-10-1614:59:52”);
将String转换为Date类型
Stringday="2014-6-510:30:30"; SimpleDateFormatd2=newSimpleDateFormat("yyyy-MM-ddHH:mm:ss"); Datedate2=d2.parse(day); System.out.println(“ThuJun0510:30:30CST2014”);
Calendar类的应用
java.util.Calendar类是一个抽象类,可以通过调用getInstance()静态方法获取一个Calendar对象,此对象已由当前日期时间初始化,即默认代表当前时间
Calendarc=Calendar.getInstance(); intyear=c.get(Calender.YEAR); intmonth=c.get(Calender.MONTH)+1;//获取月份,0表示1月份 intday=c.get(Calender.DAY_OF_MONTH); inthour=c.get(Calender.HOUR_OF_DAY); intminute=c.get(Calender.MINUTE); intsecond=c.get(Calender.SECOND);
比较2个时间相差的月份
SimpleDateFormatformat=newSimpleDateFormat("yyyy-MM-ddhh:mm:ss"); DateTimed1=newDateTime(format.parse("2016-10-3100:00:00")); DateTimed2=newDateTime(format.parse("2015-1-3100:00:00")); System.out.println(Math.abs(Months.monthsBetween(d1,d2).getMonths()));
第二部分:日期处理工具类
packagecom.analysys.website.control; importjava.text.ParseException; importjava.text.ParsePosition; importjava.text.SimpleDateFormat; importjava.util.Calendar; importjava.util.Date; importjava.util.GregorianCalendar; importorg.apache.commons.lang.StringUtils; importorg.apache.log4j.Logger; /** *日期处理工具类 *@authordylan_xu *@dateMar11,2012 *@modifiedby *@modifieddate *@sinceJDK1.6 *@seecom.util.DateUtil */ publicclassDateUtil{ //~Staticfields/initializers //============================================= privatestaticLoggerlogger=Logger.getLogger(DateUtil.class); privatestaticStringdefaultDatePattern=null; privatestaticStringtimePattern="HH:mm"; privatestaticCalendarcale=Calendar.getInstance(); publicstaticfinalStringTS_FORMAT=DateUtil.getDatePattern()+"HH:mm:ss.S"; /**日期格式yyyy-MM字符串常量*/ privatestaticfinalStringMONTH_FORMAT="yyyy-MM"; /**日期格式yyyy-MM-dd字符串常量*/ privatestaticfinalStringDATE_FORMAT="yyyy-MM-dd"; /**日期格式HH:mm:ss字符串常量*/ privatestaticfinalStringHOUR_FORMAT="HH:mm:ss"; /**日期格式yyyy-MM-ddHH:mm:ss字符串常量*/ privatestaticfinalStringDATETIME_FORMAT="yyyy-MM-ddHH:mm:ss"; /**某天开始时分秒字符串常量00:00:00*/ privatestaticfinalStringDAY_BEGIN_STRING_HHMMSS="00:00:00"; /**某天结束时分秒字符串常量23:59:59*/ publicstaticfinalStringDAY_END_STRING_HHMMSS="23:59:59"; privatestaticSimpleDateFormatsdf_date_format=newSimpleDateFormat(DATE_FORMAT); privatestaticSimpleDateFormatsdf_hour_format=newSimpleDateFormat(HOUR_FORMAT); privatestaticSimpleDateFormatsdf_datetime_format=newSimpleDateFormat(DATETIME_FORMAT); //~Methods //================================================================ publicDateUtil(){ } /** *获得服务器当前日期及时间,以格式为:yyyy-MM-ddHH:mm:ss的日期字符串形式返回 *@authordylan_xu *@dateMar11,2012 *@return */ publicstaticStringgetDateTime(){ try{ returnsdf_datetime_format.format(cale.getTime()); }catch(Exceptione){ logger.debug("DateUtil.getDateTime():"+e.getMessage()); return""; } } /** *获得服务器当前日期,以格式为:yyyy-MM-dd的日期字符串形式返回 *@authordylan_xu *@dateMar11,2012 *@return */ publicstaticStringgetDate(){ try{ returnsdf_date_format.format(cale.getTime()); }catch(Exceptione){ logger.debug("DateUtil.getDate():"+e.getMessage()); return""; } } /** *获得服务器当前时间,以格式为:HH:mm:ss的日期字符串形式返回 *@authordylan_xu *@dateMar11,2012 *@return */ publicstaticStringgetTime(){ Stringtemp=""; try{ temp+=sdf_hour_format.format(cale.getTime()); returntemp; }catch(Exceptione){ logger.debug("DateUtil.getTime():"+e.getMessage()); return""; } } /** *统计时开始日期的默认值 *@authordylan_xu *@dateMar11,2012 *@return */ publicstaticStringgetStartDate(){ try{ returngetYear()+"-01-01"; }catch(Exceptione){ logger.debug("DateUtil.getStartDate():"+e.getMessage()); return""; } } /** *统计时结束日期的默认值 *@authordylan_xu *@dateMar11,2012 *@return */ publicstaticStringgetEndDate(){ try{ returngetDate(); }catch(Exceptione){ logger.debug("DateUtil.getEndDate():"+e.getMessage()); return""; } } /** *获得服务器当前日期的年份 *@authordylan_xu *@dateMar11,2012 *@return */ publicstaticStringgetYear(){ try{ returnString.valueOf(cale.get(Calendar.YEAR)); }catch(Exceptione){ logger.debug("DateUtil.getYear():"+e.getMessage()); return""; } } /** *获得服务器当前日期的月份 *@authordylan_xu *@dateMar11,2012 *@return */ publicstaticStringgetMonth(){ try{ java.text.DecimalFormatdf=newjava.text.DecimalFormat(); df.applyPattern("00;00"); returndf.format((cale.get(Calendar.MONTH)+1)); }catch(Exceptione){ logger.debug("DateUtil.getMonth():"+e.getMessage()); return""; } } /** *获得服务器在当前月中天数 *@authordylan_xu *@dateMar11,2012 *@return */ publicstaticStringgetDay(){ try{ returnString.valueOf(cale.get(Calendar.DAY_OF_MONTH)); }catch(Exceptione){ logger.debug("DateUtil.getDay():"+e.getMessage()); return""; } } /** *比较两个日期相差的天数 *@authordylan_xu *@dateMar11,2012 *@paramdate1 *@paramdate2 *@return */ publicstaticintgetMargin(Stringdate1,Stringdate2){ intmargin; try{ ParsePositionpos=newParsePosition(0); ParsePositionpos1=newParsePosition(0); Datedt1=sdf_date_format.parse(date1,pos); Datedt2=sdf_date_format.parse(date2,pos1); longl=dt1.getTime()-dt2.getTime(); margin=(int)(l/(24*60*60*1000)); returnmargin; }catch(Exceptione){ logger.debug("DateUtil.getMargin():"+e.toString()); return0; } } /** *比较两个日期相差的天数 *@authordylan_xu *@dateMar11,2012 *@paramdate1 *@paramdate2 *@return */ publicstaticdoublegetDoubleMargin(Stringdate1,Stringdate2){ doublemargin; try{ ParsePositionpos=newParsePosition(0); ParsePositionpos1=newParsePosition(0); Datedt1=sdf_datetime_format.parse(date1,pos); Datedt2=sdf_datetime_format.parse(date2,pos1); longl=dt1.getTime()-dt2.getTime(); margin=(l/(24*60*60*1000.00)); returnmargin; }catch(Exceptione){ logger.debug("DateUtil.getMargin():"+e.toString()); return0; } } /** *比较两个日期相差的月数 *@authordylan_xu *@dateMar11,2012 *@paramdate1 *@paramdate2 *@return */ publicstaticintgetMonthMargin(Stringdate1,Stringdate2){ intmargin; try{ margin=(Integer.parseInt(date2.substring(0,4))-Integer.parseInt(date1.substring(0,4)))*12; margin+=(Integer.parseInt(date2.substring(4,7).replaceAll("-0", "-"))-Integer.parseInt(date1.substring(4,7).replaceAll("-0","-"))); returnmargin; }catch(Exceptione){ logger.debug("DateUtil.getMargin():"+e.toString()); return0; } } /** *返回日期加X天后的日期 *@authordylan_xu *@dateMar11,2012 *@paramdate *@parami *@return */ publicstaticStringaddDay(Stringdate,inti){ try{ GregorianCalendargCal=newGregorianCalendar( Integer.parseInt(date.substring(0,4)), Integer.parseInt(date.substring(5,7))-1, Integer.parseInt(date.substring(8,10))); gCal.add(GregorianCalendar.DATE,i); returnsdf_date_format.format(gCal.getTime()); }catch(Exceptione){ logger.debug("DateUtil.addDay():"+e.toString()); returngetDate(); } } /** *返回日期加X月后的日期 *@authordylan_xu *@dateMar11,2012 *@paramdate *@parami *@return */ publicstaticStringaddMonth(Stringdate,inti){ try{ GregorianCalendargCal=newGregorianCalendar( Integer.parseInt(date.substring(0,4)), Integer.parseInt(date.substring(5,7))-1, Integer.parseInt(date.substring(8,10))); gCal.add(GregorianCalendar.MONTH,i); returnsdf_date_format.format(gCal.getTime()); }catch(Exceptione){ logger.debug("DateUtil.addMonth():"+e.toString()); returngetDate(); } } /** *返回日期加X年后的日期 *@authordylan_xu *@dateMar11,2012 *@paramdate *@parami *@return */ publicstaticStringaddYear(Stringdate,inti){ try{ GregorianCalendargCal=newGregorianCalendar( Integer.parseInt(date.substring(0,4)), Integer.parseInt(date.substring(5,7))-1, Integer.parseInt(date.substring(8,10))); gCal.add(GregorianCalendar.YEAR,i); returnsdf_date_format.format(gCal.getTime()); }catch(Exceptione){ logger.debug("DateUtil.addYear():"+e.toString()); return""; } } /** *返回某年某月中的最大天 *@authordylan_xu *@dateMar11,2012 *@paramyear *@parammonth *@return */ publicstaticintgetMaxDay(intiyear,intimonth){ intday=0; try{ if(imonth==1||imonth==3||imonth==5||imonth==7 ||imonth==8||imonth==10||imonth==12){ day=31; }elseif(imonth==4||imonth==6||imonth==9||imonth==11){ day=30; }elseif((0==(iyear%4))&&(0!=(iyear%100))||(0==(iyear%400))){ day=29; }else{ day=28; } returnday; }catch(Exceptione){ logger.debug("DateUtil.getMonthDay():"+e.toString()); return1; } } /** *格式化日期 *@authordylan_xu *@dateMar11,2012 *@paramorgDate *@paramType *@paramSpan *@return */ @SuppressWarnings("static-access") publicStringrollDate(StringorgDate,intType,intSpan){ try{ Stringtemp=""; intiyear,imonth,iday; intiPos=0; charseperater='-'; if(orgDate==null||orgDate.length()<6){ return""; } iPos=orgDate.indexOf(seperater); if(iPos>0){ iyear=Integer.parseInt(orgDate.substring(0,iPos)); temp=orgDate.substring(iPos+1); }else{ iyear=Integer.parseInt(orgDate.substring(0,4)); temp=orgDate.substring(4); } iPos=temp.indexOf(seperater); if(iPos>0){ imonth=Integer.parseInt(temp.substring(0,iPos)); temp=temp.substring(iPos+1); }else{ imonth=Integer.parseInt(temp.substring(0,2)); temp=temp.substring(2); } imonth--; if(imonth<0||imonth>11){ imonth=0; } iday=Integer.parseInt(temp); if(iday<1||iday>31) iday=1; Calendarorgcale=Calendar.getInstance(); orgcale.set(iyear,imonth,iday); temp=this.rollDate(orgcale,Type,Span); returntemp; }catch(Exceptione){ return""; } } publicstaticStringrollDate(Calendarcal,intType,intSpan){ try{ Stringtemp=""; Calendarrolcale; rolcale=cal; rolcale.add(Type,Span); temp=sdf_date_format.format(rolcale.getTime()); returntemp; }catch(Exceptione){ return""; } } /** *返回默认的日期格式 *@authordylan_xu *@dateMar11,2012 *@return */ publicstaticsynchronizedStringgetDatePattern(){ defaultDatePattern="yyyy-MM-dd"; returndefaultDatePattern; } /** *将指定日期按默认格式进行格式代化成字符串后输出如:yyyy-MM-dd *@authordylan_xu *@dateMar11,2012 *@paramaDate *@return */ publicstaticfinalStringgetDate(DateaDate){ SimpleDateFormatdf=null; StringreturnValue=""; if(aDate!=null){ df=newSimpleDateFormat(getDatePattern()); returnValue=df.format(aDate); } return(returnValue); } /** *取得给定日期的时间字符串,格式为当前默认时间格式 *@authordylan_xu *@dateMar11,2012 *@paramtheTime *@return */ publicstaticStringgetTimeNow(DatetheTime){ returngetDateTime(timePattern,theTime); } /** *取得当前时间的Calendar日历对象 *@authordylan_xu *@dateMar11,2012 *@return *@throwsParseException */ publicCalendargetToday()throwsParseException{ Datetoday=newDate(); SimpleDateFormatdf=newSimpleDateFormat(getDatePattern()); StringtodayAsString=df.format(today); Calendarcal=newGregorianCalendar(); cal.setTime(convertStringToDate(todayAsString)); returncal; } /** *将日期类转换成指定格式的字符串形式 *@authordylan_xu *@dateMar11,2012 *@paramaMask *@paramaDate *@return */ publicstaticfinalStringgetDateTime(StringaMask,DateaDate){ SimpleDateFormatdf=null; StringreturnValue=""; if(aDate==null){ logger.error("aDateisnull!"); }else{ df=newSimpleDateFormat(aMask); returnValue=df.format(aDate); } return(returnValue); } /** *将指定的日期转换成默认格式的字符串形式 *@authordylan_xu *@dateMar11,2012 *@paramaDate *@return */ publicstaticfinalStringconvertDateToString(DateaDate){ returngetDateTime(getDatePattern(),aDate); } /** *将日期字符串按指定格式转换成日期类型 *@authordylan_xu *@dateMar11,2012 *@paramaMask指定的日期格式,如:yyyy-MM-dd *@paramstrDate待转换的日期字符串 *@return *@throwsParseException */ publicstaticfinalDateconvertStringToDate(StringaMask,StringstrDate) throwsParseException{ SimpleDateFormatdf=null; Datedate=null; df=newSimpleDateFormat(aMask); if(logger.isDebugEnabled()){ logger.debug("converting'"+strDate+"'todatewithmask'"+aMask+"'"); } try{ date=df.parse(strDate); }catch(ParseExceptionpe){ logger.error("ParseException:"+pe); throwpe; } return(date); } /** *将日期字符串按默认格式转换成日期类型 *@authordylan_xu *@dateMar11,2012 *@paramstrDate *@return *@throwsParseException */ publicstaticDateconvertStringToDate(StringstrDate) throwsParseException{ DateaDate=null; try{ if(logger.isDebugEnabled()){ logger.debug("convertingdatewithpattern:"+getDatePattern()); } aDate=convertStringToDate(getDatePattern(),strDate); }catch(ParseExceptionpe){ logger.error("Couldnotconvert'"+strDate+"'toadate,throwingexception"); thrownewParseException(pe.getMessage(),pe.getErrorOffset()); } returnaDate; } /** *返回一个JAVA简单类型的日期字符串 *@authordylan_xu *@dateMar11,2012 *@return */ publicstaticStringgetSimpleDateFormat(){ SimpleDateFormatformatter=newSimpleDateFormat(); StringNDateTime=formatter.format(newDate()); returnNDateTime; } /** *将指定字符串格式的日期与当前时间比较 *@authorDYLAN *@dateFeb17,2012 *@paramstrDate需要比较时间 *@return *<p> *intcode *<ul> *<li>-1当前时间<比较时间</li> *<li>0当前时间=比较时间</li> *<li>>=1当前时间>比较时间</li> *</ul> *</p> */ publicstaticintcompareToCurTime(StringstrDate){ if(StringUtils.isBlank(strDate)){ return-1; } DatecurTime=cale.getTime(); StringstrCurTime=null; try{ strCurTime=sdf_datetime_format.format(curTime); }catch(Exceptione){ if(logger.isDebugEnabled()){ logger.debug("[Couldnotformat'"+strDate+"'toadate,throwingexception:"+e.getLocalizedMessage()+"]"); } } if(StringUtils.isNotBlank(strCurTime)){ returnstrCurTime.compareTo(strDate); } return-1; } /** *为查询日期添加最小时间 * *@param目标类型Date *@param转换参数Date *@return */ @SuppressWarnings("deprecation") publicstaticDateaddStartTime(Dateparam){ Datedate=param; try{ date.setHours(0); date.setMinutes(0); date.setSeconds(0); returndate; }catch(Exceptionex){ returndate; } } /** *为查询日期添加最大时间 * *@param目标类型Date *@param转换参数Date *@return */ @SuppressWarnings("deprecation") publicstaticDateaddEndTime(Dateparam){ Datedate=param; try{ date.setHours(23); date.setMinutes(59); date.setSeconds(0); returndate; }catch(Exceptionex){ returndate; } } /** *返回系统现在年份中指定月份的天数 * *@param月份month *@return指定月的总天数 */ @SuppressWarnings("deprecation") publicstaticStringgetMonthLastDay(intmonth){ Datedate=newDate(); int[][]day={{0,30,28,31,30,31,30,31,31,30,31,30,31}, {0,31,29,31,30,31,30,31,31,30,31,30,31}}; intyear=date.getYear()+1900; if(year%4==0&&year%100!=0||year%400==0){ returnday[1][month]+""; }else{ returnday[0][month]+""; } } /** *返回指定年份中指定月份的天数 * *@param年份year *@param月份month *@return指定月的总天数 */ publicstaticStringgetMonthLastDay(intyear,intmonth){ int[][]day={{0,30,28,31,30,31,30,31,31,30,31,30,31}, {0,31,29,31,30,31,30,31,31,30,31,30,31}}; if(year%4==0&&year%100!=0||year%400==0){ returnday[1][month]+""; }else{ returnday[0][month]+""; } } /** *判断是平年还是闰年 *@authordylan_xu *@dateMar11,2012 *@paramyear *@return */ publicstaticbooleanisLeapyear(intyear){ if((year%4==0&&year%100!=0)||(year%400)==0){ returntrue; }else{ returnfalse; } } /** *取得当前时间的日戳 *@authordylan_xu *@dateMar11,2012 *@return */ @SuppressWarnings("deprecation") publicstaticStringgetTimestamp(){ Datedate=cale.getTime(); Stringtimestamp=""+(date.getYear()+1900)+date.getMonth() +date.getDate()+date.getMinutes()+date.getSeconds() +date.getTime(); returntimestamp; } /** *取得指定时间的日戳 * *@return */ @SuppressWarnings("deprecation") publicstaticStringgetTimestamp(Datedate){ Stringtimestamp=""+(date.getYear()+1900)+date.getMonth() +date.getDate()+date.getMinutes()+date.getSeconds() +date.getTime(); returntimestamp; } publicstaticvoidmain(String[]args){ System.out.println(getYear()+"|"+getMonth()+"|"+getDate()); } }
以上就是本文的全部内容,希望对大家的学习有所帮助。