java - Geting duration of 2 times -
how can duration of 2 strings in format yyyymmddthhmmss
?
i´m trying using calendar class , checking gettimeinmillis()
. problem having is not consistent. idea doing wrong? every time run program 40-70 lines of output console when should none.
public class durationtester { /** * duration between 2 given times * @param time1 yyyymmddthhmmss * @param time2 yyyymmddthhmmss * @return minutes between time1 , time2 */ public static int getduration(string time1, string time2){ int yyyy1 = integer.parseint(time1.substring(0,4)); int mm1 = integer.parseint(time1.substring(4,6)); int dd1 = integer.parseint(time1.substring(6,8)); int hh1 = integer.parseint(time1.substring(9,11)); int min1 = integer.parseint(time1.substring(11,13)); int yyyy2 = integer.parseint(time2.substring(0,4)); int mm2 = integer.parseint(time2.substring(4,6)); int dd2 = integer.parseint(time2.substring(6,8)); int hh2 = integer.parseint(time2.substring(9,11)); int min2 = integer.parseint(time2.substring(11,13)); calendar cal1 = calendar.getinstance(); cal1.set(yyyy1, mm1, dd1, hh1, min1, 0); calendar cal2 = calendar.getinstance(); cal2.set(yyyy2, mm2, dd2, hh2, min2, 0); long millisec = cal1.gettimeinmillis()-cal2.gettimeinmillis(); long nonnegativems = math.abs(millisec); long seconds = nonnegativems / 1000; long minutes = seconds / 60; return (int)minutes; } public static void main(string[] args){ string t1 = "20130108t150000"; string t2 = "20130108t131500"; int errors = 0; for(int i=0; i<5000; i++){ int duration = getduration(t1,t2); if(duration == 104){ system.out.println("error: should 105 ("+errors++ +")"); } } } }
that's documented bug.
try clearing calendar before set:
cal1.clear(); cal1.set(yyyy1, mm1, dd1, hh1, min1, 0); cal2.clear(); cal2.set(yyyy2, mm2, dd2, hh2, min2, 0);
Comments
Post a Comment