Question

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?

Was it helpful?

Solution

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));

OTHER TIPS

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"
    }
}
  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

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

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top