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) {
Solution 1:
var date = newDate(1313564400000);
var month = date.getMonth();
etc.
This will be in the user's browser's local time.
Solution 2:
Instead of using parse
, which is used to convert a date string to a Date
, just pass it into the Date
constructor:
var date=newDate(timestamp);
Make sure your timestamp is a Number
, of course.
Solution 3:
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 = newDate(timestamp); // Thu Apr 09 2020 14:28:32 GMT+0100 (British Summer Time)let year = date.getFullYear(); // 2020let 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(); // 14let minute = date.getMinutes(); // 28let second = date.getSeconds(); // 32let millisecond = date.getMilliseconds(); // 345let 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 = newDate(parseFloat(timestamp));
or for right now:
var date = newDate(Date.now());
More info if you want it here (2017).
Post a Comment for "Javascript: Get Month/year/day From Unix Timestamp"