0

I got a code like this:

  var date = new Date(new Date() + dateAdjust*3600*1000 );

However, the result came out weird. But if I change the plus sign to a minus sign, and make the dateAdjust become negative, it results right. I think it considers dateAdjust36001000 as a string. How do I fix that? I heard some people say to use parseInt(), but it doesn't work either.

  var date = new Date(new Date() + parseInt(dateAdjust*3600*1000) );
Rubén
  • 34,714
  • 9
  • 70
  • 166
Flyson
  • 1
  • 1
  • 2

1 Answers1

1

Please bear in mind that JavaScript operators doesn't work exactly as Google Sheets operators (mentioned because the question includes the google-sheets tag).

The fix might be to use new Date().getTime() or new Date().toValue(). This will return the date-time in milliseconds since January 1, 1970 00:00:00 UTC. Assuming that dateAjust has assigned a number, then the final code might be:

  var date = new Date(new Date().getTime() + dateAdjust * 3600 * 1000 );

Explanation

In JavaScript, when using + having a Date object to the left, due to JavaScript rules, it's converted into a string. This happens because in JavaScript the + could make two possible operations, mathematical addition and string concatenation while - operator is only able to do a mathematical subtraction. This is a operation called type coercion.

Having a string to the left of +, makes the right operand to be converted into a string too.

Related

Rubén
  • 34,714
  • 9
  • 70
  • 166