Java, How to subtract Date objects whilst considering DST -
i have piece of code used calculate number of days between 2 date objects, , in instances, works fine. however, if date range between 2 objects includes end of march, result 1 less should be. e.g march 31 2014 - march 29 2014 = 1, whereas should 2.
i understand due fact march has 30 days of 24 hours , 1 day of 23 hours due dst, cause of value being 1 less.
however, not sure best way account missing hour.
// have int numdays = (int) ((dateto.gettime() - datefrom.gettime()) / (1000 * 60 * 60 * 24)); // have tried rounding, since should have 23 hours left over, didn't work. int numdays = (math.round(dateto.gettime() - datefrom.gettime()) / (1000 * 60 * 60 * 24));
any help/pointers appreciated.
i , have use java 7 , not able use jodatime unfortunately.
your second example close. parentheses math.round()
surround subtraction, though, since that's integer (well, long
really), nothing happens, , divide. other problem second bit of code doing integer division truncates part after decimal point. try this:
long numdays2 = math.round((dateto.gettime() - datefrom.gettime()) / (1000.0 * 60 * 60 * 24));
(as indicated, changed math.round()
parens, , made floating point division making divisor double
.)
as indicated comments, though, hack. in particular, tell there 2 days between 6am march 5 , 8pm march 6. it's not want. try on size instead:
simpledateformat fmt = new simpledateformat("yyyy-mm-dd"); calendar cal = calendar.getinstance(); cal.settime(fmt.parse("2014-03-29")); long start = cal.gettimeinmillis(); start += cal.gettimezone().getoffset(start); cal.settime(fmt.parse("2014-03-31")); long end = cal.gettimeinmillis(); end += cal.gettimezone().getoffset(end); system.out.println((end - start)/86400000.0);
is ugly? yes. weird? yes. work? yes (i think so). note i'm providing double
result; can apply rounding want result.
Comments
Post a Comment