I'm simply trying to convert a timestamp back into a human readable date but what I get when converted is strange and wrong.
This is how I save the timestamp:
var timestamp = Number(new Date());
localStorag.setItem("mytimestamp", timestamp);
and this is how I get it back and convert it to readable date:
var mydate = localStorag.getItem("mytimestamp");
var jsDate = new Date(mydate*1000);
alert(jsDate);
The jsDate
is wrong and I don't understand what's causing it!
Could someone please advise on this?
To convert timestamp to date format in JavaScript, apply the “New Date()” Constructor method to create a new date object and display the current date and time. Also, apply the “getHours()”, “getMinutes()”, and “toDateString()” methods to compile the time and date and display them.
To get a JavaScript timestamp format can be achieved using the Date() object, which holds the current time in a readable timestamp format. You can also create new Date() objects with different timestamps, and get the current Unix time using the getTime() method.
var date = new Date(timestamp * 1000); var year = date. getFullYear(); var month = date. getMonth(); var day = date. getDay(); var hour = date.
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)
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With