3

I am trying to add time to a Date object in javascript but am not getting the results that I am expecting. I am trying to pull a timer off of the page and add it to the current time to get the unix timestamp value of when the timer will hit zero. The time on the page is displayed as " HH:MM:SS ". This is what I have:

time=getTimerText.split(":");
seconds=(time[0]*3600+time[1]*60+time[2])*1000;

to convert the time into milliseconds.

fDate=new Date();
fDate.setTime(fDate.getTime()+seconds);

add the milliseconds to the javascript timestamp

alert(Math.round(fDate.getTime() / 1000));

convert the javascript timestamp to a unix timestamp

Since the timer is counting down I should get the same result every time i run the script, but I don't. Can anyone see what I might be doing wrong here?

3
  • Can you give some examples of what you are getting? Commented Apr 7, 2010 at 21:43
  • I was getting inconsistent results. I think that it was because time[2] was being added as a string to the time[0]*3600+...+ Hopefully that was the only problem. Commented Apr 7, 2010 at 21:47
  • With a question like this some example results help us figure out the problem (although Andy E's head figured it out anyway). Commented Apr 7, 2010 at 21:57

2 Answers 2

1

I just tested your calculation with a similar one of my own, splitting a string before calculating. I think I see the problem -- try explicity converting time[2] to a number:

seconds=(time[0]*3600+time[1]*60+(+time[2]))*1000;

(+time[2]) uses the unary + operator to convert a string type to a number type.

0

You're missing the fact that if you add 12 hours to the day when daylight savings time goes into effect, you'll be an hour off (or two if that's how large the offset is).

Example:

  1. Start with this string: "31/03/2013 12:00:00"
  2. convert the date string to a date object: fDate = 31/03/2013 00:00:00 GMT+1
  3. add 12 hours, 0 minutes to fDate: fDate = 31/03/2013 13:00:00 GMT+2

Why? Because at 02:00 (AM) on the 31st of March you add an hour for daylight savings time (in Sweden), so 12 hours after midnight on the 31st is 13:00 (1:00 PM).

Here's code that will compensate for time zone changes before and after you add your time:

fDate.setTime(fDate.getTime() - fDate.getTimezoneOffset() * 60000);
fDate.setTime(fDate.getTime() + seconds);
fDate.setTime(fDate.getTime() + fDate.getTimezoneOffset() * 60000);

Not the answer you're looking for? Browse other questions tagged or ask your own question.