我想做的事情是:
Date date = new Date(); // current date
date = date - 300; // substract 300 days from current date and I want to use this "date"
怎么做呢?
我想做的事情是:
Date date = new Date(); // current date
date = date - 300; // substract 300 days from current date and I want to use this "date"
怎么做呢?
当前回答
有了Java 8,现在真的很简单:
LocalDate date = LocalDate.now().minusDays(300);
关于新api的指南可以在这里找到。
其他回答
java8时间API:
Instant now = Instant.now(); //current date
Instant before = now.minus(Duration.ofDays(300));
Date dateBefore = Date.from(before);
简单地使用这个来获取300天之前的日期,用你的日期替换300天:
Date date = new Date(); // Or where ever you get it from
Date daysAgo = new DateTime(date).minusDays(300).toDate();
在这里,
DateTime 是 org.joda.time.DateTime;
Date是java.util.Date
我已经创建了一个函数,使任务更容易。
dateString: dateCalculate(dateString,"yyyy-MM-dd",7); dateString (dateString,"yyyy-MM-dd",-7);
public static String dateCalculate(String dateString, String dateFormat, int days) {
Calendar cal = Calendar.getInstance();
SimpleDateFormat s = new SimpleDateFormat(dateFormat);
try {
cal.setTime(s.parse(dateString));
} catch (ParseException e) {
e.printStackTrace();
}
cal.add(Calendar.DATE, days);
return s.format(cal.getTime());
}
您还可以使用Duration类。如。
Date currentDate = new Date();
Date oneDayFromCurrentDate = new Date(currentDate.getTime() - Duration.ofDays(1).toMillis());
在Java 8中,你可以这样做:
Instant inst = Instant.parse("2018-12-30T19:34:50.63Z");
// subtract 10 Days to Instant
Instant value = inst.minus(Period.ofDays(10));
// print result
System.out.println("Instant after subtracting Days: " + value);