Saturday 15 May 2010

java - SimpleDateFormat format date between to dates issue -



java - SimpleDateFormat format date between to dates issue -

i need calculate period between 2 dates, 1 date now. , i'm using simpledateformat formatting date.

public string getperiod(date enddate) { string format; date = new date(); long period = enddate.gettime() - now.gettime(); if (now.after(enddate)) { homecoming "passed"; } else { if (period < 1000 * 60 * 60) format = "m'm' s's'"; else if (period < 1000 * 60 * 60 * 24) format = "k'h' m'm'"; else format = "'too much'"; simpledateformat formatter = new simpledateformat(format); homecoming formatter.format(new date(period)) + " / testing - " + period / 3600000 + " hours"; } }

as result have next input illustration if enddate equals wed nov 12 13:30:02 eet 2014 (est):

1 h 36 m / testing - 22 hours

as can see test calculation , format's method result not match. doing wrong?

the difference due timezone. example, in case, given parameter time in hour, 3h output, because date thu jan 01 03:00:00 eet 1970. notice eet (i'm eastern europe).

your code work if you'd notify java utilize gmt time, says in new date(long) description:

allocates date object , initializes represent specified number of milliseconds since standard base of operations time known "the epoch", namely jan 1, 1970, 00:00:00 gmt.

also, maintain in mind date not give perfect results. using programatically determined dates 1h appart (no millies / minutes difference), date calculations give offset of 59 minutes, 59 seconds , 999 milies. if require more exact values, should utilize nanoseconds.

however, other commenters right. should not utilize java date / calendar in such way, bug mill (this 1 corner case). should check out other libraries (such yoda time), or if need simple calculations such this, yourself.

hope helps.

java

No comments:

Post a Comment