java中日期的加减

时间:2022-02-26 14:54:00
public static String getFormatTenSecondTimeBefore(String time) {
SimpleDateFormat format1 = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'.000Z'");
SimpleDateFormat format2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String utcDate = "";
try {
Date date = format2.parse(time);//传入的time 格式是yyyy-mm-dd HH:mm:ss
//下面两行是增加的代码。有疑问查询getUTC方法
String formatTenSceondBefore = format2.format((new Date(date.getTime() - 10 * 1000)));
date = format2.parse(formatTenSceondBefore);
format1.setTimeZone(TimeZone.getTimeZone("utc"));
utcDate = format1.format(date);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return utcDate;

}




//具体实现:java.text.SimpleDateFormat

//java.util.Date
       
    Date date=new Date();   
   SimpleDateFormat df=new SimpleDateFormat("yyyy-MM-dd");   
   System.out.println("三天前的日期:" + df.format(new Date(date.getTime() - 3* 24 * 60 * 60 * 1000)));  
   System.out.println("三天后的日期:" + df.format(new Date(date.getTime() + 3 * 24 * 60 * 60 * 1000)));