Asia Rajewska
Asia Rajewska

Reputation: 53

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?

Upvotes: 5

Views: 2538

Answers (4)

Kamal Pundir
Kamal Pundir

Reputation: 277

I think add and subtract days to javascript dates like this

var today= new Date();
var addDay=30;
today.setDate(today.getDate()+addDay);

Now today is pointing the next 30th date from today

Upvotes: 0

Dagg Nabbit
Dagg Nabbit

Reputation: 76736

This is a bit tricky to find in the spec, because it's not with the rest of the Date stuff.

If you take a look at section 11.6.1, "The Addition operator," you'll find the following note:

NOTE 1 No hint is provided in the calls to ToPrimitive in steps 5 and 6. All native ECMAScript objects except Date objects handle the absence of a hint as if the hint Number were given; Date objects handle the absence of a hint as if the hint String were given. Host objects may handle the absence of a hint in some other manner.

In context, that means using the addition operator (+) with a Date object will use the string value rather than the numeric value. In this sense, Date objects are special and unlike any other kind of objects.

Note that there is no such exception for the subtraction operator, as it is unambiguous — it only works for numeric subtraction; it doesn't operate on strings.

Also note that this applies to the addition operator, a + with operands on both sides. The unary "plus" operator does not work like this, so +myDateObj with nothing on the left hand side will result in the numeric value.

Upvotes: 2

Bartosz Marcinkowski
Bartosz Marcinkowski

Reputation: 6861

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)

Upvotes: 3

xdazz
xdazz

Reputation: 160833

For -, that is the minus operator, using the .valueOf method of the date object.

While for +, that is first considered as string concatenation.

today - 2 * DAY is considered as today.valueOf() - 2 * DAY

today + 2 * DAY is considered as today.toString() + 2 * DAY

So if you want to use math operation on date object, use today.getTime() instead of just today.

Upvotes: 2

Related Questions