Javascript: Convert timestamp to human readable date?
The cause of the issue here is when you multiply the timestamp by 1000.
If you simply pass myDate
to the Date
constructor you should get the correct time -
var timestamp = Number(new Date());
localStorage.setItem("mytimestamp", timestamp);
// ...
var mydateStr = localStorage.getItem("mytimestamp");
var myDate = Number(mydateStr); // convert the string back to a number
var jsDate = new Date(mydate);
It's true that Javascript deals with milliseconds but since you are generating the timestamp with Javascript and then reading it back also with Javascript, no conversion is needed - you can use the value as-is.
As was pointed out to me by @manish in the comments, the value stored in localStorage will be a string - remember to convert it back to a number before passing it to the Date constructor.
Here is an easy solution using the toDateString()
method:
const date = new Date(timestamp).toDateString();
console.log(date);
This will return something like: Thu Jul 14 2016
You can use the Number
data type instead of date * 1000
to achieve this. See code example below:
// generate a timestamp
var timestamp = Number(new Date()) //1479895361931
Then
// get the date representation from the timestamp
var date = new Date(timestamp) // Wed Nov 23 2016 18:03:25 GMT+0800 (WITA)
Try using moment.js
. It add functions such as
moment().format('MMMM Do YYYY, h:mm:ss a'); // November 23rd 2016, 12:03:36 pm
moment().format('dddd'); // Wednesday
moment().format("MMM Do YY"); // Nov 23rd 16
moment().format('YYYY [escaped] YYYY'); // 2016 escaped 2016
moment().format(); // 2016-11-23T12:03:36+02:00