Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

adding / subtracting time in JS

Lately I was playing with JS and I found something interesting. That is what I wrote into chrome console:

today = new Date()
-> Mon Apr 29 2013 13:06:01 GMT+0200 (CEST)
DAY = 1000 * 3600 * 24
-> 86400000
today - 2 * DAY
-> 1367060761452
today + 2 * DAY
-> "Mon Apr 29 2013 13:06:01 GMT+0200 (CEST)172800000"

And I am wondering why am I getting different types of answer depending on the type of operation - adding / subtracting. When I do something like that:

today - (-2) * DAY

everything is fine. Is there any ideology, or is it a bug?

like image 262
Asia Rajewska Avatar asked Mar 24 '23 03:03

Asia Rajewska


1 Answers

today + 2 * DAY uses concatenation of strings. If you want do it properly, use today.getTime().

Example:

tomorrow = new Date()
tomorrow.setTime(today.getTime() + DAY)
like image 132
Bartosz Marcinkowski Avatar answered Apr 10 '23 10:04

Bartosz Marcinkowski