JAVA 求當前日期的下一天、下一週、下一個月,向前求解也類似
阿新 • • 發佈:2019-01-04
JAVA中時間格式很多,在求解時,比較方便呼叫
1、求解下一天
public static String getNextDay(String now){ Date nowdate; String nday=new String(); SimpleDateFormat sdf=new SimpleDateFormat("yyyyMMdd"); try{ nowdate=sdf.parse(now); long oneday=1000*3600*24; Date nextday=new Date(nowdate.getTime()+oneday); nday = sdf.format(nextday.getTime()); }catch(Exception e ){ e.printStackTrace(); } return nday; }
主要用到的是JAVA中Date型別獲取毫秒數
2、求解一週
3、求解下一個月public static String getNextWeek(String now){ Date nowdate; String nweek=new String(); SimpleDateFormat sdf=new SimpleDateFormat("yyyyMMdd"); try{ nowdate=sdf.parse(now); long oneday=1000*3600*24; Date nextweek=new Date(nowdate.getTime()+oneday*(9-nowdate.getDay())); nweek = sdf.format(nextweek.getTime()); }catch(Exception e ){ e.printStackTrace(); } return nweek; }
public static String getNextMonth(String now){ Date t; String nmonth=new String(); SimpleDateFormat sdf=new SimpleDateFormat("yyyyMM"); try{ t=sdf.parse(now); Date nextmonth=new Date((t.getYear()+(t.getMonth()+1)/12),(t.getMonth()+1)%12,t.getDate()); nmonth = sdf.format(nextmonth.getTime()); }catch(Exception e ){ e.printStackTrace(); } return nmonth; }
4、求解下一個
public static String getNextHour(String now){
Date nowdate;
String nhour=new String();
SimpleDateFormat sdf=new SimpleDateFormat("yyyyMMdd HH");
try{
nowdate=sdf.parse(now);
long onehour=1000*3600;
Date nextday=new Date(nowdate.getTime()+onehour);
nhour= sdf.format(nextday.getTime());
}catch(Exception e ){
e.printStackTrace();
}
return nhour;
}