Search code examples
javaandroiddatecalendar

Subtracting and comparing Dates


I have found some similar Que's on SO but had not find the solution.

I have today's Date as following: (Let's say this as Date1 and it's value as 2012-06-22)

    Calendar cal = Calendar.getInstance();
    SimpleDateFormat dateformatter = new SimpleDateFormat("yyyy-MM-dd");
    Date start = cal.getTime();
    String currentDate=dateformatter.format(start);

I'm retrieving 4 values from the user:

  • Particular Date (Assume 5)
  • Particular Month (Assume 1)
  • Particular Year (Assume 2012)
  • No. of days (Assume 7)

So this date, say Date2 becomes 2012-01-05 (yyyy-MM-dd) along with No. of days set to 7.


I want to compare Date 1 and Date 2-No. of days.

I know that by using following snippet, particular no. of days can be subtracted from a calender instance.

Calendar calendar = Calendar.getInstance();
calendar.add(Calendar.DATE, -7);

But since I'm having Date2 in form of String, I'm not able to follow this approach.

Any help appreciated.

Edit:

From your suggestions, I'll be able to convert String to Date by using parse method of SimpleDateFormat.

Now I've 2 Date Objects.

  • How do I find Difference between them in terms of days, months, and years?
  • How to Subtract particular no. of days, say 7, from a particular date, say 2012-01-05?

Solution

  • use SimpleDateFormat to convert String (representing date) to Date

    For example :

    Date parsedDate  = new SimpleDateFormat("yyyy-MM-dd").parse("2012-01-05");