The Artima Developer Community
Sponsored Link

Java Answers Forum
Adding/subtracting dates

1 reply on 1 page. Most recent reply: Apr 18, 2007 6:16 AM by Dave H

Welcome Guest
  Sign In

Go back to the topic listing  Back to Topic List Click to reply to this topic  Reply to this Topic Click to search messages in this forum  Search Forum Click for a threaded view of the topic  Threaded View   
Previous Topic   Next Topic
Flat View: This topic has 1 reply on 1 page
Vickie Martin

Posts: 2
Nickname: jasmine14
Registered: Apr, 2004

Adding/subtracting dates Posted: Apr 17, 2007 6:41 AM
Reply to this message Reply
Advertisement
The following code is adding 5 hours to the resultant time. I need to be able to add/substract dates, and it just isn't working right. Any ideas?


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


Dave H

Posts: 16
Nickname: slebtack
Registered: Apr, 2007

Re: Adding/subtracting dates Posted: Apr 18, 2007 6:16 AM
Reply to this message Reply
Your local timezone is five hours out from GMT. You're in the USA or Canada, in the east but not on the coast?

You can't add times, any more than you can add places. You can add durations, the length of time between two instants in time, just like you can add distances between places.

The Date class represents instants in time. It does not represent durations.

Try subtracting the Date for midnight on the 1st January 1970 from your dates before adding them, then subtracting it from the answer.

Flat View: This topic has 1 reply on 1 page
Topic: Adding/subtracting dates Previous Topic   Next Topic Topic: Help with RMI

Sponsored Links



Google
  Web Artima.com   

Copyright © 1996-2019 Artima, Inc. All Rights Reserved. - Privacy Policy - Terms of Use