1

I'm having trouble adding minutes to a date in javascript in Node.js. I have a date object, bt_time = new Date()

bt_time.toString()
"Mon Mar 07 2016 03:30:10 GMT+0000 (UTC)"

The following operations attempting to add 5 minutes to the give the following results

bt_time + (60*1000*5)
"Mon Mar 07 2016 03:30:10 GMT+0000 (UTC)300000"

new Date(bt_time + (60*1000*5)).toString()
"Mon Mar 07 2016 03:30:10 GMT+0000 (UTC)"

new Date(bt_time) + (60*1000*5)
"Mon Mar 07 2016 03:30:10 GMT+0000 (UTC)300000"

It seems like the + (60*1000*5) is just tacking 300000 at the end of the date string, instead of adding to the time. I don't have the same issue when I attempt subtraction.

I need the date arithmetic to be able to iterate spans of days, 5 minutes at a time.

3
  • 2
    How about bt_time.setMinutes(bt_time.getMinutes() + 5); Commented Mar 21, 2016 at 3:58
  • @Pointy, will that be able to advance the date to the next hour, at the top of the hour? Or advance to the next day beyond 23:59 Commented Mar 21, 2016 at 4:00
  • 2
    Yes, it will. Adding to any of the Date fields will result in a proper date reflecting the difference. Commented Mar 21, 2016 at 4:03

2 Answers 2

4

Re:

I don't have the same issue when I attempt subtraction

because the subtraction operator - forces it's operands to Number, so:

bt_time - (60*1000*5)

is effectively:

bt_time.getTime() - 300000

which will create a number (that represents milliseconds since the ECMAScript epoch) with a value 300,000 smaller than the time value of bt_time.

Already answered, but for completeness:

However, the addition operator + is overloaded, so in:

bt_time + (60*1000*5)

the script engine has to work out whether it means addition, concatenation or coercion to a number (+ unary operator). By default, a Date object coerces to string, so + acts as a concatenation operator and as Daishi Nakajima says, is effectively:

bt_time.toString() +  300000
Sign up to request clarification or add additional context in comments.

Comments

3

bt_time is object type. bt_time + i means bt_time.toString() + i

correct is

new Date(bt_time.getTime() + 60*1000*5).toString();
// or
bt_time.setMinutes(bt_time.getMinutes() + 5);

I recommend moment.js in nodejs

moment().add(5, 'minutes').toDate();

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.