我做了很多搜索试图找到这个解决方案。在 Java 中搞乱日期让我很头疼。我发现的大多数结果都是使用数学来查找以前的日期或查找与今天日期的日期偏移量。我确实需要预定日期(不是今天)的东西。在找到我需要的东西之前,我弄乱了很多类和代码。
这也是我在这里发表的第一篇文章。我是一名资深潜伏者。我希望这可以节省别人寻找此内容的时间。
提交日期为 2014 年 12 月 2 日,并查找前一周的日期。
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
public class FilenameDateFormat {
SimpleDateFormat fileDateFormat = new SimpleDateFormat("yyyyMMdd");
public static void main(String[] args) throws ParseException {
new FilenameDateFormat("20141202", -7);
}
public FilenameDateFormat(String dateArg, int offsetDays) throws ParseException {
Date fileDate = fileDateFormat.parse(dateArg);
Calendar cal = new GregorianCalendar();
cal.setTime(fileDate);
cal.add(Calendar.DAY_OF_MONTH, offsetDays);
System.out.println(cal.getTime());
}
}
结果 2014 年美国东部时间 11 月 25 日星期二 00:00:00
最佳答案
为什么不使用新的 java.time api ?这可以在 java 8 中轻松完成。https://docs.oracle.com/javase/8/docs/api/java/time/package-summary.html
关于java - 对非今天的日期使用偏移量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41766711/