javascripthtmlnangettime

new Date().getTime() showing NaN in JavaScript


I am trying to save the current time inside a temporary object inside the timestamp key using new Date.getTime() and push it into an array which is inside a globally accessible variable, GLOBAL_VAR. But after I make the temporary variable and print its value it shows the timestamp is NaN I don't know why I can't get it inside the object (the console.log() and the result is shown below)

Also, handleOrderMessage function is called when a socket.io event is received I don't know if that will affect the new Date.getTime() function, showing output:

console.log("TEMP OBJECT IS", tempObject)
/*
{
id: "-909e-11ea-9ede-066a42ffe1ae",
​price: "0.1",
​quantity: "0.1",
​side: "buy",
​timestamp: NaN
}
*/
    function handleOrderMessage(msg) {


        let d = new Date();
        console.log(d.getTime());
        if (msg['status'] === "PLACED") {
            //for buy
            if (msg['orderSide'] === "Buy") {
                let tempObject = {
                    side: "buy",
                    id: msg["OrderID"],
                    timestamp: d.getTime(),
                    quantity: parseFloat(msg["Quantity"].toFixed(4)).toString(),
                    price: parseFloat(msg["Price"].toFixed(4)).toString()
                }
                //pushing to the global orders with price from msg as key
                if (tempObject.price in GLOBAL_VAR.bidOrdersPricesAsKey) {
                    GLOBAL_VAR.bidOrdersPricesAsKey[tempObject.price].push(tempObject);
                } else {
                    GLOBAL_VAR.bidOrdersPricesAsKey[tempObject.price] = [tempObject]
                }
                console.log("GLOBAL VAR BUY ORDERS PRICES ASK KEY", GLOBAL_VAR.bidOrdersPricesAsKey)
                console.log("TEMP OBJECT IS", tempObject)
      }
    }

Solution

  • Following seems to be working fine, not sure why you're getting NaN. Please provide full working code to troubleshoot the issue.

    doit();
    function doit() {
      let d = new Date();
      let tempObject = {
        side: "buy",
        timestamp: d.getTime()
      };
      console.log(tempObject);
    }