2

I have two dates 20-03-2011 and 1-04-2011,stored as String.How can I parse this into date format and calculate the difference between the two dates?

Jens Schauder
  • 77,657
  • 34
  • 181
  • 348
rak
  • 147
  • 3
  • 4
  • 14
  • 1
    First you need to parse them to `Date` (search for `SimpleDateFormat` on SO) and the simply subtract `date.getTime()`. Result is in milliseconds. – Tomasz Nurkiewicz Mar 19 '12 at 09:28
  • @TomaszNurkiewicz I tried the below code ,but shows error as unparseable date.DateFormat formatter ; Date date1 ; Date date2; formatter = new SimpleDateFormat("dd/MMM/yy"); try { date1 = (Date)formatter.parse(LeaveStartDate); System.out.println("date1--------"+date1); } catch (ParseException e) { // TODO Auto-generated catch block e.printStackTrace(); } – rak Mar 19 '12 at 09:35
  • @rak Your dates "20-03-2011" and "1-04-2011" don't have the format `dd/MMM/yy`. – Jesper Mar 19 '12 at 10:09

7 Answers7

4

The following is one solution, as there are numerous ways we can achieve this:

 import java.util.*; 
 int syear = 2000;
 int eyear = 2000;
 int smonth = 2;//Feb
 int emonth = 3;//Mar
 int sday = 27;
 int eday = 1;
 Date startDate = new Date(syear-1900,smonth-1,sday);
 Date endDate = new Date(eyear-1900,emonth-1,eday);
 int difInDays = (int) ((endDate.getTime() - startDate.getTime())/(1000*60*60*24));
kundan bora
  • 3,821
  • 2
  • 20
  • 29
1

Parsing explained here: Parse A Java Date

And calculating differences here: https://stackoverflow.com/a/3100373/66686

Community
  • 1
  • 1
Jens Schauder
  • 77,657
  • 34
  • 181
  • 348
  • The way of calculating diff on that link is retarded - would never guess somebody would use while loop for DateDiff. So - it's much better using any of the answers available on this page. – nikib3ro Aug 24 '12 at 05:20
1

You could use joda-time :

public void diff(String str1, String str2)
    {
        DateTimeFormatter FMT = DateTimeFormat.forPattern("dd-mm-yyyy");
        final DateTime dt1 = new DateTime(FMT.parseDateTime(str1));
        final DateTime dt2 = new DateTime(FMT.parseDateTime(str2));
        Days days = Days.daysBetween(dt1, dt2);
    }
NimChimpsky
  • 46,453
  • 60
  • 198
  • 311
0

use parse function in java.text.DateFormat

redDevil
  • 1,909
  • 17
  • 25
0

Try this:

long getDateDiff(String str1, String str2) throws ParseException {

    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd-MM-yyyy");
    Date date1 = simpleDateFormat.parse(str1);
    Date date2 = simpleDateFormat.parse(str2);

    return date2.getTime() - date1.getTime();
}
pmajcher
  • 537
  • 6
  • 14
0

This is a small program I whipped up to illustrate how you might want to do this. Beware, though, it may contain bugs, as I've only tested it with a handful of example dates.

You should always thoroughly unit test any code containing date calculations, as the Java API for doing all this stuff is very clunky, and always seems to produce buggy code. When possible, use a nicer Date and Time API, such as JodaTime, which is what is used at my work place.


import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

public class DateFun {

   public static void main(String[] args) throws ParseException {
      String dateOne = "20-03-2011 06:44:03 GMT";
      String dateTwo = "25-03-2011 23:12:59 GMT";
      String format = "dd-MM-yyyy HH:mm:ss z";
      System.out.println(getDiff(parseDateString(format, dateTwo), 
                  parseDateString(format, dateOne)));
      dateOne = "20-03-2011 GMT";
      dateTwo = "1-04-2011 GMT";
      format = "dd-MM-yyyy z";
      System.out.println(getDiff(parseDateString(format, dateOne), 
                  parseDateString(format, dateTwo)));
   }

   private static Calendar parseDateString(final String format, 
                  final String date) throws ParseException {
      final Date parsed = new SimpleDateFormat(format).parse(date);
      final Calendar cal = Calendar.getInstance();
      cal.setTime(parsed);
      return cal;
   }

   private static TimeDiff getDiff(final Calendar calOne, final Calendar calTwo) {
      return new TimeDiff(Math.abs(calOne.getTimeInMillis() - calTwo.getTimeInMillis()));
   }

   private static class TimeDiff {
      private static final long MS_IN_SECOND = 1000;
      private static final long MS_IN_MINUTE = MS_IN_SECOND * 60;
      private static final long MS_IN_HOUR = MS_IN_MINUTE * 60;
      private static final long MS_IN_DAY = MS_IN_HOUR * 24;
      private final long days;
      private final long hours;
      private final long minutes;
      private final long seconds;
      private final long milliseconds;
      TimeDiff(final long msDiff) {
         long msRemainder = msDiff;
         days = msRemainder / MS_IN_DAY;
         msRemainder = msRemainder - (days * MS_IN_DAY);
         hours = msRemainder / MS_IN_HOUR;
         msRemainder = msRemainder - (hours * MS_IN_HOUR);
         minutes = msRemainder / MS_IN_MINUTE;
         msRemainder = msRemainder - (minutes * MS_IN_MINUTE);
         seconds = msRemainder / MS_IN_SECOND;
         msRemainder = msRemainder - (seconds * MS_IN_SECOND);
         milliseconds = msRemainder;
      }

      @Override
      public String toString() {
         return "TimeDiff[days: " + days + ", hours: " + 
                  hours + ", minutes: " + minutes + 
                  ", seconds: " + seconds + ", milliseconds: " + 
                  milliseconds + "]";
      }
   }
}

If anyone spots a bug in this, do let me know.

Jon
  • 3,510
  • 6
  • 27
  • 32
0

Please try below code:

public void compareDate(String date1, String date2){
        SimpleDateFormat format = new SimpleDateFormat("dd-MM-yyyy");
    Calendar calendar1 = Calendar.getInstance();
    Calendar calendar2 = Calendar.getInstance();
    calendar1.setTime(format.parse(date1));
    calendar2.setTime(format.parse(date2));
    long milliseconds1 = calendar1.getTimeInMillis();
    long milliseconds2 = calendar2.getTimeInMillis();
    long diff = milliseconds2 - milliseconds1;
    long diffSeconds = diff / 1000;
    long diffMinutes = diff / (60 * 1000);
    long diffHours = diff / (60 * 60 * 1000);
    long diffDays = diff / (24 * 60 * 60 * 1000);
    System.out.println("\nThe Date Different Example");
    System.out.println("Time in milliseconds: " + diff+ " milliseconds.");
    System.out.println("Time in seconds: " + diffSeconds+ " seconds.");
    System.out.println("Time in minutes: " + diffMinutes + " minutes.");
    System.out.println("Time in hours: " + diffHours + " hours.");
    System.out.println("Time in days: " + diffDays + " days.");
}
kandarp
  • 4,979
  • 11
  • 34
  • 43