125

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'));}
3
  • 12
    Besides all the answers here, the de facto standard in js date/time handling currently is moment.js surprised no one mentioned it here Commented Oct 8, 2014 at 13:37
  • 2
    @alonisser—perhaps because converting a time value to a Date is trivial. Formatting it isn't particularly difficult either. Commented Dec 24, 2014 at 4:46
  • function getDateString() { var monthArr = [ "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec", ]; let date = new Date(); var dateTodayStr = date.getDate() + "" + monthArr[date.getMonth()] + "" + date.getFullYear() + "_" + date.getHours() + "" + ("0" + date.getMinutes()).slice(-2) + "_" + ("0" + date.getSeconds()).slice(-2); return dateTodayStr; } Commented May 16, 2022 at 8:54

12 Answers 12

172

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:

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.

Sign up to request clarification or add additional context in comments.

10 Comments

There is also togmtstring(), but deprecated. I do not get why there is tolocalestring() as in JS, everything is local in the browser. Or is toLocaleString a separation to Nodejs? If you use serverside JS, and the timezone between client and server differs, you get the client zone?
@timo—the use of "locale" is a misnomer for a method that attempts to present a format that is consistent with the formatting preferences of the user. Unfortunately it's based on the language, which is not a particularly good determinant of preferred format. It would preferable to format dates based on system preferences for date formatting rather than the much less specific language code.
This helped me thanks. To remove GMT use - .toDateString()
@devssh—the use of Date.parse in new Date(Date.parse(string)) is entirely redundant, new Date(string) must produce an identical result. Using the built–in parser to parse unsupported string formats is strongly discouraged as parsing is implementation dependent. If you want to post an answer, do that at the duplicate.
@devssh— new Date(Date.parse(string)) and new Date(string) must produce identical results per ECMA-262 so the use of Date.parse is redundant. "2024/01/31" is not a supported format (i.e. by ECMA-262), parsing is implementation dependent. Until recently, Safari treated it as an invalid date. The time value generated by parsing "2024/01/31" depends on system settings and may be NaN. "2024-Jan-31" is not a supported format either. YYYY-MM-DD is parsed as UTC, all other date–only forms are implementation dependent and treated as local (probably). Read the spec.
|
48

This works fine. Checked in chrome browser:

var theDate = new Date(timeStamp_value * 1000);
dateString = theDate.toGMTString();
alert(dateString );

4 Comments

toGMTString() is deprecated, use toISOString() or toUTCString() instead
Caution *-*: don't multiply by 1000. Else, you'll hyperloop into future space!!
after multiply 1586855504 with 1000 I got right result otherwise it was providing 1970
multiplication by 1000 depends on what your timestamp is in, seconds or milliseconds
36

why not simply

new Date (timestamp);

A date is a date, the formatting of it is a different matter.

Comments

29

Moment.js can convert unix timestamps into any custom format

In this case : var time = moment(1382086394000).format("DD-MM-YYYY h:mm:ss");

will print 18-10-2013 11:53:14;

Here's a plunker that demonstrates this.

1 Comment

Sounds like this is overkill
16

Here are the simple ways to every date format confusions:

for current date:

var current_date=new Date();

to get the Timestamp of current date:

var timestamp=new Date().getTime();

to convert a particular Date into Timestamp:

var timestamp_formation=new Date('mm/dd/yyyy').getTime();

to convert timestamp into Date:

    var timestamp=new Date('02/10/2016').getTime();
    var todate=new Date(timestamp).getDate();
    var tomonth=new Date(timestamp).getMonth()+1;
    var toyear=new Date(timestamp).getFullYear();
    var original_date=tomonth+'/'+todate+'/'+toyear;

  OUTPUT:
 02/10/2016

3 Comments

yes @melpomene, half of the code is irrelevant but i wrote that to clear further doubts on date formation..!!!and one more thing i didn't copied it from anywhere. I tried it in my own code and 2 days back i worked on it
It doesn't matter whether you literally copied it or not. The point is that all the information is already there in another answer. By the way, your last example doesn't actually produce the output you claim it does.
output shown doesn't actually match the code output(2/10/2016)
10

we need to create new function using JavaScript.

function unixTime(unixtime) {

    var u = new Date(unixtime*1000);

      return u.getUTCFullYear() +
        '-' + ('0' + u.getUTCMonth()).slice(-2) +
        '-' + ('0' + u.getUTCDate()).slice(-2) + 
        ' ' + ('0' + u.getUTCHours()).slice(-2) +
        ':' + ('0' + u.getUTCMinutes()).slice(-2) +
        ':' + ('0' + u.getUTCSeconds()).slice(-2) +
        '.' + (u.getUTCMilliseconds() / 1000).toFixed(3).slice(2, 5) 
    };

console.log(unixTime(1370001284))

2016-04-30 08:36:26.000

Comments

7

Use .toLocaleString:

// undefined uses default locale
console.log(new Date().toLocaleString(undefined, {dateStyle: 'short'}));

Or custom method in case you don't want to use the toLocaleString for some reason:

formatDate is the function you can call it and pass the date you want to format to dd/mm/yyyy

var unformatedDate = new Date("2017-08-10 18:30:00");
 
$("#hello").append(formatDate(unformatedDate));
function formatDate(nowDate) {
    return nowDate.getDate() +"/"+ (nowDate.getMonth() + 1) + '/'+ nowDate.getFullYear();
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="hello">


</div>

Comments

6

This is what I did for the Instagram API. converted timestamp with date method by multiplying by 1000. and then added all entity individually like (year, months, etc)

created the custom month list name and mapped it with getMonth() method which returns the index of the month.

convertStampDate(unixtimestamp){


// Months array
var months_arr = ['January','February','March','April','May','June','July','August','September','October','November','December'];

// Convert timestamp to milliseconds
var date = new Date(unixtimestamp*1000);

// Year
var year = date.getFullYear();

// Month
var month = months_arr[date.getMonth()];

// Day
var day = date.getDate();

// Hours
var hours = date.getHours();

// Minutes
var minutes = "0" + date.getMinutes();

// Seconds
var seconds = "0" + date.getSeconds();

// Display date time in MM-dd-yyyy h:m:s format
var fulldate = month+' '+day+'-'+year+' '+hours + ':' + minutes.substr(-2) + ':' + seconds.substr(-2);

// final date
var convdataTime = month+' '+day;
return convdataTime;
}

Call with stamp argument convertStampDate('1382086394000')

and that's it.

Comments

4

There is a simple way to convert to a more readable form

new Date().toLocaleString();
new Date(1630734254000).toLocaleString();

Outputs in this format => 9/4/2021, 11:14:14 AM

1 Comment

Also please make sure that timestamp has 13 digits you might want to multiply with 1000 to get desired output
3

My ES6 variant produces a string like this 2020-04-05_16:39:45.85725. Feel free to modify the return statement to get the format that you need:

const getDateStringServ = timestamp => {

  const plus0 = num => `0${num.toString()}`.slice(-2)

  const d = new Date(timestamp)

  const year = d.getFullYear()
  const monthTmp = d.getMonth() + 1
  const month = plus0(monthTmp)
  const date = plus0(d.getDate())
  const hour = plus0(d.getHours())
  const minute = plus0(d.getMinutes())
  const second = plus0(d.getSeconds())
  const rest = timestamp.toString().slice(-5)

  return `${year}-${month}-${date}_${hour}:${minute}:${second}.${rest}`
}

Comments

1
new Date(timestamp).toString().substring(4, 15)

1631685556789 ==> Sep 15 2021

2 Comments

I'm trying to convert 1664632339 and get Jan 20 1970 yet all online converters say it's October 1 2022
You need to pass timestamp in milliseconds. Pass "1664632339000" instead of "1664632339" and you will get the correct value.
-3

To calculate date in timestamp from the given date

//To get the timestamp date from normal date: In format - 1560105000000

//input date can be in format : "2019-06-09T18:30:00.000Z"

this.calculateDateInTimestamp = function (inputDate) {
    var date = new Date(inputDate);
    return date.getTime();
}

output : 1560018600000

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.