Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript: Convert timestamp to human readable date?

Tags:

javascript

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?

like image 976
David Hope Avatar asked Nov 23 '16 10:11

David Hope


People also ask

How to convert timestamp to date in JavaScript?

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.

How to get readable time JavaScript?

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.

How to convert Unix timestamp to human readable in JavaScript?

var date = new Date(timestamp * 1000); var year = date. getFullYear(); var month = date. getMonth(); var day = date. getDay(); var hour = date.


2 Answers

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)
like image 135
Natsathorn Avatar answered Oct 17 '22 11:10

Natsathorn


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

like image 34
Constantine Kobylinskyi Avatar answered Oct 17 '22 12:10

Constantine Kobylinskyi