Yang
Yang

Reputation: 6912

javascript: get month/year/day from unix timestamp

I have a unix timestamp, e.g., 1313564400000.00. How do I convert it into Date object and get month/year/day accordingly? The following won't work:

function getdhm(timestamp) {
        var date = Date.parse(timestamp);
        var month = date.getMonth();
        var day = date.getDay();
        var year = date.getYear();

        var formattedTime = month + '/' + day + '/' + year;
        return formattedTime;

    }

Upvotes: 19

Views: 72600

Answers (3)

Adam Marsh
Adam Marsh

Reputation: 1156

An old question, but none of the answers seemed complete, and an update for 2020:

For example: (you may have a decimal if using microsecond precision, e.g. performance.now())

let timestamp = 1586438912345.67;

And we have:

var date = new Date(timestamp); // Thu Apr 09 2020 14:28:32 GMT+0100 (British Summer Time)
let year = date.getFullYear(); // 2020
let month = date.getMonth() + 1; // 4 (note zero index: Jan = 0, Dec = 11)
let day = date.getDate(); // 9

And if you'd like the month and day to always be a two-digit string (e.g. "01"):

let month = (date.getMonth() + 1).toString().padStart(2, '0'); // "04"
let day = date.getDate().toString().padStart(2, '0'); // "09"

For extended completeness:

let hour = date.getHours(); // 14
let minute = date.getMinutes(); // 28
let second = date.getSeconds(); // 32
let millisecond = date.getMilliseconds(); // 345
let epoch = date.getTime(); // 1586438912345 (Milliseconds since Epoch time)

Further, if your timestamp is actually a string to start (maybe from a JSON object, for example):

var date = new Date(parseFloat(timestamp));

or for right now:

var date = new Date(Date.now());

More info if you want it here (2017).

Upvotes: 8

Jim Blackler
Jim Blackler

Reputation: 23179

var date = new Date(1313564400000);
var month = date.getMonth();

etc.

This will be in the user's browser's local time.

Upvotes: 30

Jacob
Jacob

Reputation: 78920

Instead of using parse, which is used to convert a date string to a Date, just pass it into the Date constructor:

var date = new Date(timestamp);

Make sure your timestamp is a Number, of course.

Upvotes: 7

Related Questions