Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Function to convert timestamp to human date in javascript

How to convert this timestamp 1382086394000 to 2013-10-18 08:53:14 using a function in javascript? Currently I have this function:

function cleanDate(d) {return new Date(+d.replace(/\/Date\((\d+)\)\//, '$1'));} 
like image 326
Willy Mularto Avatar asked Oct 21 '13 02:10

Willy Mularto


2 Answers

The value 1382086394000 is probably a time value, which is the number of milliseconds since 1970-01-01T00:00:00Z. You can use it to create an ECMAScript Date object using the Date constructor:

var d = new Date(1382086394000); 

How you convert that into something readable is up to you. Simply sending it to output should call the internal (and entirely implementation dependent) toString method* that usually prints the equivalent system time in a human readable form, e.g.

Fri Oct 18 2013 18:53:14 GMT+1000 (EST)  

In ES5 there are some other built-in formatting options:

  • toDateString
  • toTimeString
  • toLocaleString

and so on. Note that most are implementation dependent and will be different in different browsers. If you want the same format across all browsers, you'll need to format the date yourself, e.g.:

alert(d.getDate() + '/' + (d.getMonth()+1) + '/' + d.getFullYear()); 

* The format of Date.prototype.toString has been standardised in ECMAScript 2018. It might be a while before it's ubiquitous across all implementations, but at least the more common browsers support it now.

like image 72
RobG Avatar answered Oct 01 '22 05:10

RobG


This works fine. Checked in chrome browser:

var theDate = new Date(timeStamp_value * 1000); dateString = theDate.toGMTString(); alert(dateString ); 
like image 44
Optimus Krish Avatar answered Oct 01 '22 05:10

Optimus Krish