Friday, 15 April 2011

Wrong output from Java Calendar API -



Wrong output from Java Calendar API -

calendar.settimeinmillis , calendar.gettime works weird. returns wrong date results.

java code

public static void main(string[] args) { calendar cal = calendar.getinstance(); final int oneday = 24 * 60 * 60 * 1000; for(int i=0; < 30; i++) { cal.settimeinmillis(system.currenttimemillis() - * oneday); system.out.println(cal.gettime()); } }

output

tue jun 24 17:50:35 ist 2014 mon jun 23 17:50:35 ist 2014 sun jun 22 17:50:35 ist 2014 sat jun 21 17:50:35 ist 2014 fri jun 20 17:50:35 ist 2014 thu jun 19 17:50:35 ist 2014 wed jun 18 17:50:35 ist 2014 tue jun 17 17:50:35 ist 2014 mon jun 16 17:50:35 ist 2014 sun jun 15 17:50:35 ist 2014 sat jun 14 17:50:35 ist 2014 fri jun 13 17:50:35 ist 2014 thu jun 12 17:50:35 ist 2014 wed jun 11 17:50:35 ist 2014 tue jun 10 17:50:35 ist 2014 mon jun 09 17:50:35 ist 2014 sun jun 08 17:50:35 ist 2014 sat jun 07 17:50:35 ist 2014 fri jun 06 17:50:35 ist 2014 thu jun 05 17:50:35 ist 2014 wed jun 04 17:50:35 ist 2014 tue jun 03 17:50:35 ist 2014 mon jun 02 17:50:35 ist 2014 sun jun 01 17:50:35 ist 2014 sat may 31 17:50:35 ist 2014 sat jul 19 10:53:23 ist 2014 fri jul 18 10:53:23 ist 2014 thu jul 17 10:53:23 ist 2014 wed jul 16 10:53:23 ist 2014 tue jul 15 10:53:23 ist 2014

after "may 31" , "may 30 , may 29 , may 28 & may 27" returns wrong date.

sat may 31 17:50:35 ist 2014 sat jul 19 10:53:23 ist 2014 fri jul 18 10:53:23 ist 2014 thu jul 17 10:53:23 ist 2014 wed jul 16 10:53:23 ist 2014 tue jul 15 10:53:23 ist 2014

is bug in calendar.gettime()?

no, not bug in calendar.gettime().

you using int, , when numbers become big fit in int, i * oneday overflows , unusual results.

solution: utilize long instead:

final long oneday = 24l * 60 * 60 * 1000;

(your code doesn't take daylight savings account, @ point you'll see shift of hr if timezone has daylight savings).

java calendar

No comments:

Post a Comment