Java对日期Date类进行加减运算、年份加减月份加减、时间差等等
实现代码一:
importjava.text.SimpleDateFormat; importjava.util.Calendar; importjava.util.Date; publicclassDateTestUtil{ publicstaticvoidmain(String[]args)throwsException{ SimpleDateFormatsdf=newSimpleDateFormat("yyyyMMdd"); Stringstr="20110823"; Datedt=sdf.parse(str); CalendarrightNow=Calendar.getInstance(); rightNow.setTime(dt); rightNow.add(Calendar.YEAR,-1);//日期减1年 rightNow.add(Calendar.MONTH,3);//日期加3个月 rightNow.add(Calendar.DAY_OF_YEAR,10);//日期加10天 Datedt1=rightNow.getTime(); StringreStr=sdf.format(dt1); System.out.println(reStr); } }
注:在Calendar对象的add方法中,第二个参数为正数表示“加”,负数表示“减”。
代码二:javadate日期加减天数
测试类代码:
importjava.text.SimpleDateFormat; importjava.util.Date; publicclassDateTest{ publicstaticvoidmain(String[]arg){ Datenow=newDate(); addAndSubtractDaysByGetTime(now,-5); addAndSubtractDaysByGetTime(now,5); addAndSubtractDaysByCalendar(now,-5); addAndSubtractDaysByCalendar(now,5); } publicstaticDateaddAndSubtractDaysByGetTime(DatedateTime/*待处理的日期*/,intn/*加减天数*/){ //日期格式 SimpleDateFormatdf=newSimpleDateFormat("yyyy-MM-dd"); SimpleDateFormatdd=newSimpleDateFormat("yyyy-MM-ddHH:mm:ss"); System.out.println(df.format(newDate(dateTime.getTime()+n*24*60*60*1000L))); //System.out.println(dd.format(newDate(dateTime.getTime()+n*24*60*60*1000L))); //注意这里一定要转换成Long类型,要不n超过25时会出现范围溢出,从而得不到想要的日期值 returnnewDate(dateTime.getTime()+n*24*60*60*1000L); } publicstaticDateaddAndSubtractDaysByCalendar(DatedateTime/*待处理的日期*/,intn/*加减天数*/){ //日期格式 SimpleDateFormatdf=newSimpleDateFormat("yyyy-MM-dd"); SimpleDateFormatdd=newSimpleDateFormat("yyyy-MM-ddHH:mm:ss"); java.util.Calendarcalstart=java.util.Calendar.getInstance(); calstart.setTime(dateTime); calstart.add(java.util.Calendar.DAY_OF_WEEK,n); System.out.println(df.format(calstart.getTime())); //System.out.println(dd.format(calstart.getTime())); returncalstart.getTime(); } }
运行结果:
2014-10-06
2014-10-16
2014-10-06
2014-10-16
代码三:
在网上查阅资料,加上自己总结的一些关于Date类的工具类。
packagecom.data.utils; importjava.text.SimpleDateFormat; importjava.util.Calendar; importjava.util.Date; publicclassDateFormat{ /** *日期减几年 */ publicstaticStringdateMinusYear(Stringstr)throwsException{ SimpleDateFormatsdf=newSimpleDateFormat("yyyyMM"); Datedt=sdf.parse(str); CalendarrightNow=Calendar.getInstance(); rightNow.setTime(dt); rightNow.add(Calendar.YEAR,-1);//日期减1年 Datedt1=rightNow.getTime(); StringreStr=sdf.format(dt1); returnreStr; } /** *日期加几年 */ publicstaticStringdateAddYear(Stringstr)throwsException{ SimpleDateFormatsdf=newSimpleDateFormat("yyyyMM"); Datedt=sdf.parse(str); CalendarrightNow=Calendar.getInstance(); rightNow.setTime(dt); rightNow.add(Calendar.YEAR,1);//日期加1年 Datedt1=rightNow.getTime(); StringreStr=sdf.format(dt1); returnreStr; } /** *日期减几月 */ publicstaticStringdateMinusMonth(Stringstr)throwsException{ SimpleDateFormatsdf=newSimpleDateFormat("yyyyMM"); Datedt=sdf.parse(str);//将字符串生成Date CalendarrightNow=Calendar.getInstance(); rightNow.setTime(dt);//使用给定的Date设置此Calendar的时间。 rightNow.add(Calendar.MONTH,-1);//日期减1个月 Datedt1=rightNow.getTime();//返回一个表示此Calendar时间值的Date对象。 StringreStr=sdf.format(dt1);//将给定的Date格式化为日期/时间字符串,并将结果添加到给定的StringBuffer。 returnreStr; } /** *日期加几月 */ publicstaticStringdateAddMonth(Stringstr)throwsException{ SimpleDateFormatsdf=newSimpleDateFormat("yyyyMM"); Datedt=sdf.parse(str); CalendarrightNow=Calendar.getInstance(); rightNow.setTime(dt); rightNow.add(Calendar.MONTH,1);//日期加3个月 //rightNow.add(Calendar.DAY_OF_YEAR,10);//日期加10天 Datedt1=rightNow.getTime(); StringreStr=sdf.format(dt1); returnreStr; } /** *获取当前年月的第一个月的str *@paramstr *201505 *@return201501 *@throwsException */ publicstaticStringdateOneMonth(Stringstr){ str=str.substring(0,str.length()-2); str=str+"01"; returnstr; } /** *算出所选月份距离一月份有几个月。 *@paramstr201509 *@return9 */ publicstaticintdateDistanceMonth(Stringstr){ inti=Integer.parseInt(str); intj=Integer.parseInt(DateFormat.dateOneMonth(str)); System.out.println(i-j); returni-j+1; } /** *获取两个时间的时间差,精确到毫秒 *@paramstr *@return */ publicstaticStringTimeDifference(longstart,longend){ longbetween=end-start; longday=between/(24*60*60*1000); longhour=(between/(60*60*1000)-day*24); longmin=((between/(60*1000))-day*24*60-hour*60); longs=(between/1000-day*24*60*60-hour*60*60-min*60); longms=(between-day*24*60*60*1000-hour*60*60*1000 -min*60*1000-s*1000); StringtimeDifference=day+"天"+hour+"小时"+min+"分"+s+"秒"+ms +"毫秒"; returntimeDifference; } } /** *获取24小时、一周、一个月的起始时间 * *@paramtimeInterval *:DAY_TIME_INTERVALWEEK_TIME_INTERVALMONTH_TIME_INTERVAL *@return"yyyy-mm-ddhh:mm:ss" */ publicstaticStringgetStartTime(inttimeInterval){ Calendarcal=Calendar.getInstance(); SimpleDateFormatsdf=newSimpleDateFormat("yyyy-MM-ddHH:mm:ss"); if(DAY_TIME_INTERVAL==timeInterval){//获取24小时的起始时间 cal.set(Calendar.HOUR_OF_DAY,0); cal.set(Calendar.MINUTE,0); cal.set(Calendar.SECOND,0); StringstartTime=sdf.format(cal.getTime()); returnstartTime; }elseif(WEEK_TIME_INTERVAL==timeInterval){ intweekday=cal.get(Calendar.DAY_OF_WEEK)-1; cal.add(Calendar.DATE,-weekday); cal.set(Calendar.HOUR_OF_DAY,0); cal.set(Calendar.MINUTE,0); cal.set(Calendar.SECOND,0); StringstartTime=sdf.format(cal.getTime()); returnstartTime; }elseif(MONTH_TIME_INTERVAL==timeInterval){ intdayofmonthMin=cal.getActualMinimum(Calendar.DAY_OF_MONTH); //c.add(Calendar.DATE,-dayofmonth); cal.set(Calendar.DATE,dayofmonthMin); cal.set(Calendar.HOUR_OF_DAY,0); cal.set(Calendar.MINUTE,0); cal.set(Calendar.SECOND,0); StringstartTime=sdf.format(cal.getTime()); returnstartTime; } returnnull; } /** *获取24小时、一周、一个月的结束时间 * *@paramtimeInterval *:DAY_TIME_INTERVALWEEK_TIME_INTERVALMONTH_TIME_INTERVAL *@return"yyyy-mm-ddhh:mm:ss" */ publicstaticStringgetEndTime(inttimeInterval){ Calendarcal=Calendar.getInstance(); cal.setTimeZone(TimeZone.getTimeZone("GMT+8")); SimpleDateFormatsdf=newSimpleDateFormat("yyyy-MM-ddHH:mm:ss"); if(DAY_TIME_INTERVAL==timeInterval){ cal.set(Calendar.HOUR_OF_DAY,23); cal.set(12,59); cal.set(13,59); longdate=cal.getTimeInMillis(); StringendTime=sdf.format(newDate(date)); returnendTime; }elseif(WEEK_TIME_INTERVAL==timeInterval){ intweekday=cal.get(Calendar.DAY_OF_WEEK)-1; cal.add(Calendar.DATE,-weekday); cal.add(Calendar.DATE,6); cal.set(Calendar.HOUR_OF_DAY,23); cal.set(12,59); cal.set(13,59); longdate=cal.getTimeInMillis(); StringendTime=sdf.format(newDate(date)); returnendTime; }elseif(MONTH_TIME_INTERVAL==timeInterval){ intdayOfMonthMax=cal.getActualMaximum(Calendar.DAY_OF_MONTH); cal.set(Calendar.DATE,dayOfMonthMax); cal.set(Calendar.HOUR_OF_DAY,23); cal.set(Calendar.MINUTE,59); cal.set(Calendar.SECOND,59); StringendTime=sdf.format(cal.getTime()); returnendTime; } returnnull; } /** *判断dateStr是否在start和end中间,start和end都可以为nullyyyyMMddHHmmss或者yyyyMMdd格式 * *@authoryou.xu *@date2015年8月19日下午3:11:46 *@paramdateStr *@paramstart *@paramend *@return */ publicstaticbooleancheckDateVal(StringdateStr,Stringstart,Stringend){ booleanisDateRight=false; Datedate=null; DatestartDate=null; DateendDate=null; SimpleDateFormatsdf=null; //判断日期格式 if(14==dateStr.length()){ sdf=newSimpleDateFormat("yyyyMMddHHmmss"); }elseif(8==dateStr.length()){ sdf=newSimpleDateFormat("yyyyMMdd"); }else returnfalse; try{ //更改判断日期格式 date=sdf.parse(dateStr); }catch(ParseExceptione){ log.error(e,e); } if((start==null)&&(end!=null)){ try{ endDate=sdf.parse(end); }catch(ParseExceptionex1){ log.error(ex1,ex1); } if((date!=null)&&(endDate!=null))//Checkparametersfor { if(date.compareTo(endDate)<=0) isDateRight=true; } }elseif((start!=null)&&(end==null)){ try{ startDate=sdf.parse(start); }catch(ParseExceptionex1){ log.error(ex1,ex1); } if((date!=null)&&(startDate!=null)){ if(date.compareTo(startDate)>=0) isDateRight=true; } }elseif((start!=null)&&(end!=null)){ try{ startDate=sdf.parse(start); endDate=sdf.parse(end); }catch(ParseExceptionex2){ System.out.println(ex2.toString()); } if((startDate!=null)&&(date!=null)&&(endDate!=null)){ if((date.compareTo(startDate)>=0) &&(date.compareTo(endDate)<=0)) isDateRight=true; } } returnisDateRight; } /** *判断dateStr是否在start和end中间,start和end都可以为nulllong形格式 * *@authoryou.xu *@date2015年8月19日下午3:12:35 *@paramdateStr *@paramstart *@paramend *@return */ publicstaticbooleancheckDateV(StringdateStr,Stringstart,Stringend){ booleanisDateRight=false; longdate=-1; longfromDate=-1; longtoDate=-1; date=java.lang.Long.parseLong(dateStr); if((start==null)&&(end==null)){ isDateRight=true; }elseif((start==null)&&(end!=null)){ try{ toDate=java.lang.Long.parseLong(end); }catch(NumberFormatExceptionnfe){ log.error(nfe,nfe); } if(date<=toDate){ isDateRight=true; } }elseif((start!=null)&&(end==null)){ try{ fromDate=java.lang.Long.parseLong(start); }catch(NumberFormatExceptionnfe){ log.error(nfe,nfe); } if(date>=fromDate){ isDateRight=true; } }elseif((start!=null)&&(end!=null)){ try{ toDate=java.lang.Long.parseLong(end); fromDate=java.lang.Long.parseLong(start); }catch(NumberFormatExceptionnfe){ log.error(nfe,nfe); } if((date<=toDate)&&(date>=fromDate)){ isDateRight=true; } } returnisDateRight; }
目前就用到了这些,随时添加,有简单方便的时间工具类,希望和大家一起学习,在评论中指出。thanks!!!