0

I have the following Javascript code:

var dateMilliseconds = web3.toAscii(newArray[i]).substring(0, 13)
console.log(dateMilliseconds) // returns 1500282374082
var date = new Date(dateMilliseconds)
console.log(date) // returns invalid date

If I try var date = new Date(1500282374082) instead, it works - how should I be passing the dateMilliseconds variable in properly and what type should it be?

ZhouW
  • 1,187
  • 3
  • 16
  • 39

1 Answers1

2

You need to pass this as an integer, and not a string.

You can use the +value trick to convert it into an integer:

var date = new Date(+dateMilliseconds)
CBroe
  • 91,630
  • 14
  • 92
  • 150
  • What's the deal with this "+"?. How does that convert String to Integer? – Killer Death Jul 17 '17 at 09:26
  • 1
    @KillerDeath it is one of several ways to force a string value to be converted to a number, see https://stackoverflow.com/questions/1133770/how-do-i-convert-a-string-into-an-integer-in-javascript – CBroe Jul 17 '17 at 09:28
  • 1
    @KillerDeath—it's called the [*Unary + operator*](http://ecma-international.org/ecma-262/8.0/#sec-unary-plus-operator), it "*converts its operand to Number type.*" – RobG Jul 17 '17 at 22:45
  • I know it's a unary operator, I just didn't know it has such a function in javascript. – Killer Death Jul 18 '17 at 07:32