如何在Java中获得当前的两周日期

  • 本文关键字:两周 日期 Java java date
  • 更新时间 :
  • 英文 :


我有今天的日期,格式是2014-05-08,我需要得到当前日期前2周的日期。

我应该得到的数据是- 2014-04-24

        String currentDate= dateFormat.format(date); //2014-05-08
        String dateBefore2Weeks = currentDate- 2 week;

但我不确定如何在Java中提取当前日期之前的两周日期?

使用Calendar来修改您的Date对象:

//method created for demonstration purposes
public Date getDateBeforeTwoWeeks(Date date) {
    Calendar calendar = Calendar.getInstance();
    calendar.setTime(date);
    calendar.add(Calendar.DATE, -14); //2 weeks
    return calendar.getTime();
}
在你的代码中使用上面的方法:
String currentDate= dateFormat.format(date); //2014-05-08
String dateBefore2Weeks = dateFormat.format(getDateBeforeTwoWeeks(date));

Java现在有一个非常好的内置日期库Java。

import java.time.LocalDate;
public class Foo {
    public static void main(String[] args) {
        System.out.println(LocalDate.parse("2014-05-08").minusWeeks(2));
        // prints "2014-04-24"
    }
}
  1. 使用SimpleDateFormat将日期解析为日期对象
  2. 使用Calendar对象从该日期减去14天
  3. 使用相同的SimpleDateFormat格式化结果日期

值得一看joda-time API [http://joda-time.sourceforge.net/userguide.html]。

最新更新