开发者

Time difference while taking into a/c

If we have 2 dates Previous Date : Wed Jun 02 17:30:00 CDT 2010 Next Date : Sun Feb开发者_高级运维 13 22:00:00 CST 2011 and need to find difference in mins. between these 2 dates

Is there a way to accurately get it?


Yes, you can get an accurate difference of those times:

  1. Parse each one with SimpleDateFormat to get a Date.
  2. Get the time in milliseconds since the Epoch from each.
  3. Subtract the two times and divide by 60000 for minutes.

Here's the code:

SimpleDateFormat sdf = new SimpleDateFormat("EEE MMM dd HH:mm:ss zzz yyyy");
Date prevDate = sdf.parse("Wed Jun 02 17:30:00 CDT 2010");
Date nextDate = sdf.parse("Sun Feb 13 22:00:00 CST 2011");
long diffTime = nextDate.getTime() - prevDate.getTime();
System.out.println(diffTime / 60000 + " minutes");


date1.getTime() - date2.getTime() will give you the difference in milliseconds. You can then divide it by 60000 to get the difference in minutes.


Use TimeUnit class for convertion.

    // specify the input format
    SimpleDateFormat dateFormat = new SimpleDateFormat("EEE MMM dd HH:mm:ss zzz yyyy");
    String s1 = "Wed Jun 02 17:30:00 CDT 2010";
    String s2 = "Sun Feb 13 22:00:00 CST 2011";
    // parse to Date object
    Date d1 = dateFormat.parse(s1); 
    Date d2 = dateFormat.parse(s2);
    // get time in milliseconds
    long l1 = d1.getTime();  
    long l2 = d2.getTime();
    // absolute difference
    long diff = Math.abs(l1 - l2); 
    // convert milliseconds to minute
    long min = TimeUnit.MILLISECONDS.toMinutes(diff); 
    System.out.println(min);


With Joda Time

DurationFormatUtils.formatDuration(date2.getTime() - date1.getTime(), "m");
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜