Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add time to a Date object in javascript

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?

like image 463
Aaron Luman Avatar asked May 22 '26 15:05

Aaron Luman


1 Answers

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.

like image 116
Andy E Avatar answered May 24 '26 06:05

Andy E



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!