Adding time issue using Date's getTime method

The following code is incorrectly adding 5 hours to the resultant time.

I need to be able to add dates, and this just isn't working right.

Is this a bug or am I missing something?

long msecSum = 0 ;

DateFormat dateFormat = new SimpleDateFormat("HH:mm:ss.SSS") ;

try

{

Date date1 = dateFormat.parse("01:02:05.101") ;

Date date2 = dateFormat.parse("02:03:10.102") ;

System.out.println("Date1: " + dateFormat.format(date1));

System.out.println("Date2: " + dateFormat.format(date2));

msecSum = date1.getTime() + date2.getTime() ; // adds 5 hours !!!

System.out.println("Sum: " + dateFormat.format(msecSum)) ;

}

catch (Exception e)

{

System.out.println("Unable to process time values");

}

Results:

Date1: 01:02:05.101

Date2: 02:03:10.102

Sum: 08:05:15.203 // should be 3 hours, not 8

[917 byte] By [jasmine14a] at [2007-11-27 1:22:57]
# 1

Dates shouldn't be added, but if you promise not to tell anyone:

long msecSum = 0 ;

DateFormat dateFormat = new SimpleDateFormat("HH:mm:ss.SSS") ;

dateFormat.setTimeZone(TimeZone.getTimeZone("GMT"));

try

{

Date date1 = dateFormat.parse("01:02:05.101") ;

Date date2 = dateFormat.parse("02:03:10.102") ;

System.out.println("Date1: " + dateFormat.format(date1));

System.out.println("Date2: " + dateFormat.format(date2));

msecSum = date1.getTime() + date2.getTime() ; // adds 5 hours !!!

System.out.println("Sum: " + dateFormat.format(msecSum)) ;

}

catch (Exception e)

{

System.out.println("Unable to process time values");

Me? I would just parse the String "01:02:05.101" to extract hours,

minutes, seconds and milliseconds and do the math.

DrLaszloJamfa at 2007-7-12 0:10:51 > top of Java-index,Java Essentials,Java Programming...
# 2
Maybe what OP is looking for is Calendar.roll()? see: http://java.sun.com/j2se/1.5.0/docs/api/java/util/Calendar.html
notivagoa at 2007-7-12 0:10:51 > top of Java-index,Java Essentials,Java Programming...