Search code examples
javascriptdateunixtimestampunix-timestamp

Convert day date to Unix Timestamp


How can i convert day date (for example, 22 which stands for 1/22/2017) to Unix Timestamp (after conversion result needs to be 1485079018) in javascript.

I tried code below without luck.

var d = new Date();
var n = d.getDate();
var g = Math.round(new Date().getDate()/1000);

Solution

  • to Unix Timestamp (after conversion result needs to be 1485079018

    The Unix timestamp 1485079018 is Jan 22 2017 at 09:56:58 UTC. Where are you getting that 09:56:58 from?

    In terms of the problem, if I assume you actually want midnight UTC rather than 09:56:58, see comments:

    var day = 22;
    // Create the date (in UTC)
    var dt = new Date(Date.UTC(2017, 0, day));
    // Or not UTC, but then we get really far afield of Unix timestamps:
    //var dt = new Date(2017, 0, day);
    var ts = Math.round(dt / 1000);
    console.log(ts);