0

I m trying to get difference in miliseconds between current time and a certain day say 2013/12/25

I am using this code

Calendar thatDay = Calendar.getInstance();
thatDay.set(Calendar.DAY_OF_MONTH,25);
thatDay.set(Calendar.MONTH,11); // 0-11 so 1 less
thatDay.set(Calendar.YEAR, 2013);


Calendar today = Calendar.getInstance();

long diff =  thatDay.getTimeInMillis() - today.getTimeInMillis(); 
long days = diff / (24 * 60 * 60 * 1000);

but this code some times give right value some time slightly difference..please help guys

flx
  • 14,146
  • 11
  • 55
  • 70
Brett
  • 431
  • 2
  • 10
  • 26
  • while precisely not your answer, but i will suggest you to take a look at `date4j` library. very simple api to get difference and basic date stuffs. here http://www.date4j.net/ – Rachit Mishra Dec 04 '13 at 13:30
  • You can also look jodatime library(http://joda-time.sourceforge.net/installation.html) for that. – Dhruvil Patel Dec 04 '13 at 13:32
  • "this code some times give right value some time slightly difference" what kind of difference? if you integer divide the result you'll truncate 3.9 days to 3 and that would be 1 day off. Is that what happens? – zapl Dec 04 '13 at 13:35
  • @zapl: a difference of one day. 20 or 21. but it have nothing to do with the long. you can use double and the result is 21.0 or 20.0 – kai Dec 04 '13 at 13:39
  • @zapl .. yes you r right.. that is my problem.. – Brett Dec 04 '13 at 16:02

1 Answers1

1

In places that observe daylight savings time one day in a year is 23 hours long, and another is 25 hours long, so it's wrong to assume that each day is 24 hours long. Official time zones can also change.

The "correct" way to fix the issue is using well designed library such as Joda time, but as a quick fix you can round the result so that deviations of a few hours to one direction or another don't matter:

long days = Math.round((double) diff / (24 * 60 * 60 * 1000);
Joni
  • 108,737
  • 14
  • 143
  • 193
  • thanx for your answer.. If i want to convert it in day:hor:minute:seconds format then what i have to do? – Brett Dec 05 '13 at 04:18
  • That format doesn't make much sense unless you assume a fixed number of hours per day – Joni Dec 05 '13 at 07:12