3

I have two Dates. How can I tell the difference between these two dates in days?

I have heard of SimpleDateFormat, but I don't know how to use it.

I tried this:

String fromdate = "Apr 10 2011";

SimpleDateFormat sdf;
sdf = new SimpleDateFormat("MMM DD YYYY"); 

sdf.parse(fromdate);

Calendar cal = Calendar.getInstance();
cal.setTime(sdf);

I also tried this:

String date1 = "APR 11 2011";
String date2 = "JUN 02 2011";
String format = "MMM DD YYYY";
SimpleDateFormat sdf = new SimpleDateFormat(format);
Date dateObj1 = sdf.parse(date1);
Date dateObj2 = sdf.parse(date2);
long diff = dateObj2.getTime() - dateObj1.getTime();
int diffDays = (int) (diff / (24* 1000 * 60 * 60));
System.out.println(diffDays);

but I got the exception "Illegal pattern character 'Y'."

Basil Bourque
  • 218,480
  • 72
  • 657
  • 915
Pavan
  • 93
  • 5
  • 9
  • What do you mean by *difference*? Do you want to test which one is further in time or you just want to know if they are different? – Op De Cirkel Jun 02 '11 at 18:49
  • 4
    See http://stackoverflow.com/questions/5497762/find-time-differnce and http://stackoverflow.com/questions/5194216/how-can-i-calculate-the-difference-between-two-dates and http://stackoverflow.com/questions/1116123/how-do-i-calculate-someones-age-in-java – x4u Jun 02 '11 at 18:49
  • 1
    Difference in what? Milliseconds? Days? Days, Hours, Minutes? Etc. Please note that `DD` and `YYYY` are invalid patterns for days and years. Read the javadoc: http://download.oracle.com/javase/6/docs/api/java/text/SimpleDateFormat.html – BalusC Jun 02 '11 at 18:50
  • Thank you very much , i need difference in days – Pavan Jun 02 '11 at 18:52
  • I tried this way :String date1 = "APR 11 2011"; String date2 = "JUN 02 2011"; String format = "MMM DD YYYY"; SimpleDateFormat sdf = new SimpleDateFormat(format); Date dateObj1 = sdf.parse(date1); Date dateObj2 = sdf.parse(date2); long diff = dateObj2.getTime() - dateObj1.getTime(); int diffDays = (int) (diff / (24* 1000 * 60 * 60)); System.out.println(diffDays); but gettiing a Exception "Illegal pattern character 'Y'" – Pavan Jun 02 '11 at 18:55
  • make it `y` like this String format = "MMM DD yyyy"; – Piraba Feb 24 '12 at 11:20

5 Answers5

3

The other answers are correct but outdated.

java.time

The java.time framework is built into Java 8 and later. These classes supplant the old troublesome date-time classes such as java.util.Date, .Calendar, & java.text.SimpleDateFormat. The Joda-Time team also advises migration to java.time.

To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations.

Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport and further adapted to Android in ThreeTenABP.

The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time.

LocalDate

The LocalDate class represents a date-only value without time-of-day and without time zone.

I suggest using standard ISO 8601 formats for your strings where possible. But in your case we need to specify a formatting pattern.

String input = "Apr 10 2011";

DateTimeFormatter f = DateTimeFormatter.ofPattern ( "MMM d uuuu" );
LocalDate earlier = LocalDate.parse ( input , f );

DateTimeFormatter formatterOut = DateTimeFormatter.ofLocalizedDate ( FormatStyle.MEDIUM ).withLocale ( Locale.US );
String output = earlier.format ( formatterOut );

LocalDate later = earlier.plusDays ( 13 );

long days = ChronoUnit.DAYS.between ( earlier , later );

Dump to console.

System.out.println ( "from earlier: " + earlier + " to later: " + later + " = days: " + days + " ending: " + output );

from earlier: 2011-04-10 to later: 2011-04-23 = days: 13 ending: Apr 10, 2011

Basil Bourque
  • 218,480
  • 72
  • 657
  • 915
1

You have two Date objects?

The answer could not be simpler.

public double computeDaysBetweenDates(Date d1, Date d2) {
    long diff;

    diff = d2.getTime() - d1.getTime();
    return ((double) diff) / (86400.0 * 1000.0);
}

Date objects are thin wrappers around a long that contains a UTC POSIX EPOCH time, which is the number of milliseconds that have elapsed since midnight, Jan 1, 1970 UTC. You get your interval number of milliseconds just by subtracting the earlier value from the later. Knowing that, you just divide by the number of milliseconds in a day.

Note that this answer assumes that a day is 86400 seconds and ... that is mostly true.

Note that this solution is still apt even if you have formatted date strings. If you are able to parse your date/times into Date objects first, then you can still call this function with them.

scottb
  • 9,181
  • 3
  • 38
  • 49
1

Here is an article that uses Calendar to solve this problem. http://tripoverit.blogspot.com/2007/07/java-calculate-difference-between-two.html

I believe that Joda Time also provides API support for this scenario

nsfyn55
  • 13,511
  • 7
  • 45
  • 75
  • The code on the blog post doesnt work if the dates being compared are at different times on the same day. It will return a difference of 1 when it should be 0 – robjwilkins Oct 30 '15 at 08:42
0

This code should show you how to do what you need...

public static void main(String[] args) {
    Calendar firstOfTheMonthCalendar = Calendar.getInstance();
    firstOfTheMonthCalendar.set(Calendar.DAY_OF_MONTH, 1);

    Date firstOfTheMonthDate = firstOfTheMonthCalendar.getTime();
    Date nowDate = new Date();

    int diffInDays = determineDifferenceInDays(firstOfTheMonthDate, nowDate);
    System.out.println("Number of days betweens dates: " + diffInDays);
}

private static int determineDifferenceInDays(Date date1, Date date2) {
    Calendar calendar1 = Calendar.getInstance();
    calendar1.setTime(date1);
    Calendar calendar2 = Calendar.getInstance();
    calendar2.setTime(date2);
    long diffInMillis = calendar2.getTimeInMillis() - calendar1.getTimeInMillis();
    return (int) (diffInMillis / (24* 1000 * 60 * 60));
}
Jesse Webb
  • 36,395
  • 25
  • 99
  • 138
  • I read the blog post linked to in nsfyn55's answer and it appears my solution won't work in some timezones. The articale shows a more definitive way of solving this problem but my answer should work in most cases. – Jesse Webb Jun 03 '11 at 14:10
0

Difference between two date strings in java

this will help you in getting some idea

Community
  • 1
  • 1
RanRag
  • 43,987
  • 34
  • 102
  • 155