1

I have today's date in this string format 2014-05-08 and I needed to get the date of 2 weeks prior the currents date.

So the data I should be getting back is - 2014-04-24.

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

        String dateBefore2Weeks = currentDate- 2 week;

But I am not sure how do I extract date of two weeks prior to current date in Java?

AKIWEB
  • 19,008
  • 67
  • 180
  • 294
  • This is not *exactly* a duplicate, because times have changed since then. – Chris Martin May 09 '14 at 07:43
  • @ChrisMartin If something has changed, such as the arrival of [java.time](http://docs.oracle.com/javase/8/docs/api/java/time/package-summary.html) in Java 8, then update the original question(s) and answers. – Basil Bourque May 09 '14 at 08:29

4 Answers4

8

Use Calendar to modify your Date object:

//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();
}

Use the method above in your code:

String currentDate= dateFormat.format(date); //2014-05-08
String dateBefore2Weeks = dateFormat.format(getDateBeforeTwoWeeks(date));
Luiggi Mendoza
  • 85,076
  • 16
  • 154
  • 332
2

Java now has a pretty good built-in date library, java.time bundled with Java 8.

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"
    }
}
Basil Bourque
  • 303,325
  • 100
  • 852
  • 1,154
Chris Martin
  • 30,334
  • 10
  • 78
  • 137
1
  1. Parse the date using a SimpleDateFormat into a Date object
  2. Use a Calendar object to subtract 14 days from that date
  3. Format the resulting date using the same SimpleDateFormat
Jason
  • 11,744
  • 3
  • 42
  • 46
0

worth having a look into joda-time api [http://joda-time.sourceforge.net/userguide.html].