Skip to content
Advertisement

JavaScript Date setTime one liner [closed]

Real simple question! I’m trying to create a google chart using datetime objects, which take the Date() objects in JavaScript. Since I’m looping through a bunch of data (from flask), I’d like to be able to create a new Date() object and would just like to know if I’m setting the date object correctly in one line.

Here’s what I’m using at the moment new Date().setTime(1660549080000.0) and storing this directly in a google charts column, unfortunately something is not working and I’m wondering if its this!

Edit: Ended up just making a function for it!

function timestampGen(timestamp){
        var datenew = new Date();
        datenew.setTime(timestamp);
        return datenew
    }
timestampGen(time);

Advertisement

Answer

Doing it in one line does not return a date object. The reason is setTime returns the milliseconds.

So the line you are coding is basically returning the number you are setting!

You need to do it in multiple lines.

var myDate = new Date();
myDate.setTime(1660549080000.0);
console.log(myDate);

or you can just set the value of the date constructor with the milliseconds to get your single line.

console.log(new Date(1660549080000.0));
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement