397

I have been fighting with this for a bit now. I’m trying to convert epoch to a date object. The epoch is sent to me in UTC. Whenever you pass new Date() an epoch, it assumes it’s local epoch. I tried creating a UTC object, then using setTime() to adjust it to the proper epoch, but the only method that seems useful is toUTCString() and strings don’t help me. If I pass that string into a new date, it should notice that it’s UTC, but it doesn’t.

new Date( new Date().toUTCString() ).toLocaleString()

My next attempt was to try to get the difference between local current epoch and UTC current epoch, but I wasn’t able to get that either.

new Date( new Date().toUTCString() ).getTime() - new Date().getTime()

It’s only giving me very small differences, under 1000, which is in milliseconds.

Any suggestions?

Sebastian Simon
  • 18,263
  • 7
  • 55
  • 75
Shane Reustle
  • 8,633
  • 8
  • 40
  • 51
  • 17
    The epoch time is defined as the elapsed milliseconds since the 1970 date *in UTC*. There is no such thing as a local epoch! Not sure I understand your problem. – Chetan S Jan 08 '11 at 02:13
  • Maybe the timezone on the computer is incorrect, leading to a different UTC value? – kijin Jan 08 '11 at 02:25
  • 2
    You have to set your clock to UTC time, if you want to 'see' UTC time when you use toLocaleString(). Midnight UTC is 7pm EST. If you use new Date().toString() instead of localeString you would get something like: 'Fri Jan 07 2011 07:00:00 GMT-0500 ', which includes the offset. – kennebec Jan 08 '11 at 03:29
  • Epoch unit is seconds, not milliseconds. – Teson Jan 03 '22 at 09:53

17 Answers17

651

I think I have a simpler solution -- set the initial date to the epoch and add UTC units. Say you have a UTC epoch var stored in seconds. How about 1234567890. To convert that to a proper date in the local time zone:

var utcSeconds = 1234567890;
var d = new Date(0); // The 0 there is the key, which sets the date to the epoch
d.setUTCSeconds(utcSeconds);

d is now a date (in my time zone) set to Fri Feb 13 2009 18:31:30 GMT-0500 (EST)

mikemaccana
  • 110,530
  • 99
  • 389
  • 494
user1030503
  • 6,642
  • 1
  • 14
  • 5
  • 270
    FWIW, Date objects can be initialized with milliseconds. So, `var d = new Date(utcSeconds * 1000)` should yield the same result. – kurttheviking Jan 17 '13 at 16:59
  • 83
    `var d = new Date(1234567890000)` returns the same result – Matjaz Lipus Feb 06 '14 at 10:47
  • 14
    thought maybe others could get some clarity from a couple points: the date object does not get set with a timezone "stamped in it". think of it as nothing but a number. that number is the number of milliseconds since 1970 jan 1 UTC, to now (now being in UTC also). So, whenever you create a date object, it is really in UTC behind the scenes. 2. To display that date, you can display it as the locale setting (toLocaleString(), or, in UTC (toUTCString()). you don't need to convert anything yourself. Construct with utc millisec, all good. Construct with string - so long as it's in local timezone. – da Bich Dec 02 '14 at 16:50
  • 4
    1234567890000 is treated the same as 1234567890, aka the Y39K problem... – muttonUp Jun 27 '18 at 16:43
  • this worked, but i had to divide my epoch time by 1000 cuz it was in ms – WtFudgE Nov 12 '19 at 13:48
  • 2
    @muttonUp, with 1000 mulitplication it worked. But, 'Y39K problem" google is not giving any valid result. Any URL will be helpful – Satish Patro Dec 09 '19 at 16:57
  • Cool @mikemaccana. That Thing Works. You Saved My 2 Days of Struggle. Thanks Man. – manish pamnani May 29 '20 at 03:56
  • @manishpamnani Thank user1030503, I (and some other users) just edited the answer to clean it up a little. – mikemaccana May 29 '20 at 09:37
356

It's easy, new Date() just takes milliseconds, e.g.

new Date(1394104654000)
> Thu Mar 06 2014 06:17:34 GMT-0500 (EST)
djechlin
  • 59,258
  • 35
  • 162
  • 290
  • 8
    Nice one! This should be considered as the accepted answer really. – Nizar B. Jun 08 '17 at 20:15
  • 1
    This one didn't work for me, it works when you have timestamp but with utc epoch you have to set utcseconds manually, the accept answer is the right answer – sameerali Aug 10 '17 at 09:16
  • 32
    This is an appropriate answer. New date may take milliseconds, therefore just multiply by 1000: `const d = new Date(epoch * 1000)`. – vinyll Aug 14 '17 at 10:47
  • 2
    @sameerali Perhaps you had some different problem with your system or you got confused. This answer is the correct answer. The definition of the Unix epoch: *number of seconds elapsed since January 1st midnight UTC*. Just multiply with 1000 to get the number of elapsed milliseconds. – nalply Dec 08 '17 at 09:26
  • Is this documented? – pooya13 Dec 15 '21 at 21:46
35

Epoch time is in seconds from Jan. 1, 1970. date.getTime() returns milliseconds from Jan. 1, 1970, so.. if you have an epoch timestamp, convert it to a javascript timestamp by multiplying by 1000.

   function epochToJsDate(ts){
        // ts = epoch timestamp
        // returns date obj
        return new Date(ts*1000);
   }

   function jsDateToEpoch(d){
        // d = javascript date obj
        // returns epoch timestamp
        return (d.getTime()-d.getMilliseconds())/1000;
   }
Lodder
  • 19,758
  • 10
  • 59
  • 100
logic8
  • 874
  • 9
  • 21
  • Was wondering what on earth was up. Very good to know that **epochTime !== javascriptTime** when it comes to date parsing. Thanks! – GrayedFox Mar 21 '18 at 14:59
35

And just for the logs, I did this using Moment.js library, which I was using for formatting anyway.

moment.utc(1234567890000).local()
>Fri Feb 13 2009 19:01:30 GMT-0430 (VET)
Gus
  • 718
  • 8
  • 13
  • 5
    Moment is nice, but it's insane to use a 1.3MB library to just convert one epoch to a date. No wonder there are so many bloated node apps out there. – not2qubit Feb 07 '18 at 19:27
  • 8
    I mean, he literally did specify that he's using it for formatting. Not fair to say that here. – Xevion Aug 13 '20 at 13:33
17
 function ToLocalDate (inDate) {
    var date = new Date();
    date.setTime(inDate.valueOf() - 60000 * inDate.getTimezoneOffset());
    return date;
}
chris
  • 171
  • 1
  • 3
13

Epoch time (i.e. Unix Epoch time) is nearly always the number of seconds that have expired since 1st Jan 1970 00:00:00 (UTC time), not the number of milliseconds which some of the answers here have implied.

https://en.wikipedia.org/wiki/Unix_time

Therefore, if you have been given a Unix Epoch time value it will probably be in seconds, and will look something like 1547035195. If you want to make this human readable in JavaScript, you need to convert the value to milliseconds, and pass that value into the Date(value) constructor, e.g.:

const unixEpochTimeMS = 1547035195 * 1000;
const d = new Date(unixEpochTimeMS);
// Careful, the string output here can vary by implementation...
const strDate = d.toLocaleString();

You don't need to do the d.setUTCMilliseconds(0) step in the accepted answer because the JavaScript Date(value) constructor takes a UTC value in milliseconds (not a local time).

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date#Syntax

Also note that you should avoid using the Date(...) constructor that takes a string datetime representation, this is not recommended (see the link above).

garryp
  • 5,508
  • 1
  • 29
  • 41
9

var myDate = new Date( your epoch date *1000);

source - https://www.epochconverter.com/programming/#javascript

Aldrin
  • 2,036
  • 15
  • 12
5

To convert the current epoch time in [ms] to a 24-hour time. You might need to specify the option to disable 12-hour format.

$ node.exe -e "var date = new Date(Date.now()); console.log(date.toLocaleString('en-GB', { hour12:false } ));"

2/7/2018, 19:35:24

or as JS:

var date = new Date(Date.now()); 
console.log(date.toLocaleString('en-GB', { hour12:false } ));
// 2/7/2018, 19:35:24

console.log(date.toLocaleString('en-GB', { hour:'numeric', minute:'numeric', second:'numeric', hour12:false } ));
// 19:35:24

Note: The use of en-GB here, is just a (random) choice of a place using the 24 hour format, it is not your timezone!

not2qubit
  • 14,531
  • 8
  • 95
  • 135
  • 1
    This is the best way to get any type of conversion from the Date method. Thanks! – SeaWarrior404 Jul 26 '18 at 13:00
  • The only thing I don't like with the above, is that it returns the date in a that ambiguous format of `d/m/yyyy` or is it `m/d/yyyy`? The right (most logical) way to display this should be: `yyyy-mm-dd`. Any takers? – not2qubit Apr 30 '20 at 07:50
5

Addition to the above answer by @djechlin

d = '1394104654000';
new Date(parseInt(d));

converts EPOCH time to human readable date. Just don't forget that type of EPOCH time must be an Integer.

Sarvar Nishonboyev
  • 12,262
  • 10
  • 69
  • 70
5

The Easiest Way

If you have the unix epoch in milliseconds, in my case - 1601209912824

  1. convert it into a Date Object as so
const dateObject = new Date(milliseconds)
const humanDateFormat = dateObject.toString() 

output -

Sun Sep 27 2020 18:01:52 GMT+0530 (India Standard Time)
  1. if you want the date in UTC -
const dateObject = new Date(milliseconds)
const humanDateFormat = dateObject.toUTCString() 
  1. Now you can format it as you please.

David Buck
  • 3,752
  • 35
  • 31
  • 35
4

Considering, you have epoch_time available,

// for eg. epoch_time = 1487086694.213
var date = new Date(epoch_time * 1000); // multiply by 1000 for milliseconds
var date_string = date.toLocaleString('en-GB');  // 24 hour format
apurva.nandan
  • 1,061
  • 1
  • 11
  • 19
  • You can also add an actual time zone like this: `date.toLocaleString("sv-SE", {timeZone: "Europe/Stockholm"})` List of time zones can be found in this post https://stackoverflow.com/questions/38399465/how-to-get-list-of-all-timezones-in-javascript – user1820536 Jul 30 '20 at 11:07
4

The simplest solution I've found to this, is:

var timestamp = Date.now(), // returns milliseconds since epoch time
    normalisedTime = new Date(timestamp);

Notice this doesn't have the * 1000 at the end of new Date(timestamp) statement as this (for me anyway!) always seems to give out the wrong date, ie instead of giving the year 2019 it gives the year as 51015, so just bear that in mind.

dmmfll
  • 2,666
  • 2
  • 35
  • 41
Rob P
  • 65
  • 1
  • 2
  • 7
3

EDIT

var utcDate = new Date(incomingUTCepoch);
var date = new Date();
date.setUTCDate(utcDate.getDate());
date.setUTCHours(utcDate.getHours());
date.setUTCMonth(utcDate.getMonth());
date.setUTCMinutes(utcDate.getMinutes());
date.setUTCSeconds(utcDate.getSeconds());
date.setUTCMilliseconds(utcDate.getMilliseconds());

EDIT fixed

Amjad Masad
  • 4,035
  • 1
  • 21
  • 20
  • I went through this in my second example. The differences it gives me are anywhere between 50 and 900, which is in miliseconds (showing the time during processing the calculation, not the actual difference) – Shane Reustle Jan 08 '11 at 02:11
  • None of them help me. They are missing a setUTCTime method, which would be perfect :P http://www.w3schools.com/jsref/jsref_obj_date.asp – Shane Reustle Jan 08 '11 at 02:20
  • Doesn't work, at least on Firefox for Ubuntu. Code shouldn't set day/month/year after it sets date. – Simon Kozlov Feb 12 '11 at 04:13
  • @Simon Kozlov Actually thats a wrong assumption in the date object, the setDate and getDate refer to the day in the month, and the problem is that I used functions like (setUTCDay) that doesn't exist, surprised it got accepted !! – Amjad Masad Feb 12 '11 at 04:56
  • @AmjadMasad Your answer would be more helpful if you also show the expected output. – not2qubit Feb 07 '18 at 19:29
3

Are you just asking to convert a UTC string to a "local" string? You could do:

var utc_string = '2011-09-05 20:05:15';
var local_string = (function(dtstr) {
    var t0 = new Date(dtstr);
    var t1 = Date.parse(t0.toUTCString().replace('GMT', ''));
    var t2 = (2 * t0) - t1;
    return new Date(t2).toString();
})(utc_string);
ZagNut
  • 1,431
  • 15
  • 20
2

If you prefer to resolve timestamps and dates conversions from and to UTC and local time without libraries like moment.js, take a look at the option below.

For applications that use UTC timestamps, you may need to show the date in the browser considering the local timezone and daylight savings when applicable. Editing a date that is in a different daylight savings time even though in the same timezone can be tricky.

The Number and Date extensions below allow you to show and get dates in the timezone of the timestamps. For example, lets say you are in Vancouver, if you are editing a date in July or in December, it can mean you are editing a date in PST or PDT.

I recommend you to check the Code Snippet down below to test this solution.

Conversions from milliseconds

Number.prototype.toLocalDate = function () {
    var value = new Date(this);

    value.setHours(value.getHours() + (value.getTimezoneOffset() / 60));

    return value;
};

Number.prototype.toUTCDate = function () {
    var value = new Date(this);

    value.setHours(value.getHours() - (value.getTimezoneOffset() / 60));

    return value;
};

Conversions from dates

Date.prototype.getUTCTime = function () {
    return this.getTime() - (this.getTimezoneOffset() * 60000);
};

Usage

// Adds the timezone and daylight savings if applicable
(1499670000000).toLocalDate();

// Eliminates the timezone and daylight savings if applicable
new Date(2017, 6, 10).getUTCTime();

See it for yourself

// Extending Number

Number.prototype.toLocalDate = function () {
    var value = new Date(this);

    value.setHours(value.getHours() + (value.getTimezoneOffset() / 60));

    return value;
};

Number.prototype.toUTCDate = function () {
    var value = new Date(this);

    value.setHours(value.getHours() - (value.getTimezoneOffset() / 60));

    return value;
};

// Extending Date

Date.prototype.getUTCTime = function () {
    return this.getTime() - (this.getTimezoneOffset() * 60000);
};

// Getting the demo to work
document.getElementById('m-to-local-button').addEventListener('click', function () {
  var displayElement = document.getElementById('m-to-local-display'),
      value = document.getElementById('m-to-local').value,
      milliseconds = parseInt(value);
  
  if (typeof milliseconds === 'number')
    displayElement.innerText = (milliseconds).toLocalDate().toISOString();
  else
    displayElement.innerText = 'Set a value';
}, false);

document.getElementById('m-to-utc-button').addEventListener('click', function () {
  var displayElement = document.getElementById('m-to-utc-display'),
      value = document.getElementById('m-to-utc').value,
      milliseconds = parseInt(value);
  
  if (typeof milliseconds === 'number')
    displayElement.innerText = (milliseconds).toUTCDate().toISOString();
  else
    displayElement.innerText = 'Set a value';
}, false);

document.getElementById('date-to-utc-button').addEventListener('click', function () {
  var displayElement = document.getElementById('date-to-utc-display'),
      yearValue = document.getElementById('date-to-utc-year').value || '1970',
      monthValue = document.getElementById('date-to-utc-month').value || '0',
      dayValue = document.getElementById('date-to-utc-day').value || '1',
      hourValue = document.getElementById('date-to-utc-hour').value || '0',
      minuteValue = document.getElementById('date-to-utc-minute').value || '0',
      secondValue = document.getElementById('date-to-utc-second').value || '0',
      year = parseInt(yearValue),
      month = parseInt(monthValue),
      day = parseInt(dayValue),
      hour = parseInt(hourValue),
      minute = parseInt(minuteValue),
      second = parseInt(secondValue);
  
  displayElement.innerText = new Date(year, month, day, hour, minute, second).getUTCTime();
}, false);
<link href="https://cdnjs.cloudflare.com/ajax/libs/semantic-ui/2.2.11/semantic.css" rel="stylesheet"/>

<div class="ui container">
  <p></p>
  
  <h3>Milliseconds to local date</h3>
  <input id="m-to-local" placeholder="Timestamp" value="0" /> <button id="m-to-local-button">Convert</button>
  <em id="m-to-local-display">Set a value</em>

  <h3>Milliseconds to UTC date</h3>
  <input id="m-to-utc" placeholder="Timestamp" value="0" /> <button id="m-to-utc-button">Convert</button>
  <em id="m-to-utc-display">Set a value</em>
  
  <h3>Date to milliseconds in UTC</h3>
  <input id="date-to-utc-year" placeholder="Year" style="width: 4em;" />
  <input id="date-to-utc-month" placeholder="Month" style="width: 4em;" />
  <input id="date-to-utc-day" placeholder="Day" style="width: 4em;" />
  <input id="date-to-utc-hour" placeholder="Hour" style="width: 4em;" />
  <input id="date-to-utc-minute" placeholder="Minute" style="width: 4em;" />
  <input id="date-to-utc-second" placeholder="Second" style="width: 4em;" />
  <button id="date-to-utc-button">Convert</button>
  <em id="date-to-utc-display">Set the values</em>
  
</div>
Darlesson
  • 5,742
  • 2
  • 21
  • 26
  • This is the actual answer. Worked like a charm for me. Setting new Date(0) and adding milliSeconds is the same as new Date(milliSeconds) – Jersey_Guy Oct 12 '17 at 21:54
1

I have converted the epoch time by using Intl.DateTimeFormat(). The input time is in milliseconds.

here is code example that I used:

let options = {
  year: "numeric",
  month: "numeric",
  day: "numeric",
  hour: "numeric",
  minute: "numeric",
  second: "numeric",
  hour12: false,
  timeZone: Intl.DateTimeFormat().resolvedOptions().timeZone,
};

export const epochTime = (time) => { 
  return new Intl.DateTimeFormat("en-US", options).format(new Date(time)); // returns DD/MM/YYYY hh:mm ss
};

References:

  1. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl
  2. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat
Shahmir
  • 31
  • 6
0

@Amjad, good idea, but a better implementation would be:

Date.prototype.setUTCTime = function(UTCTimestamp) {
    var UTCDate = new Date(UTCTimestamp);
    this.setUTCFullYear(UTCDate.getFullYear(), UTCDate.getMonth(), UTCDate.getDate());
    this.setUTCHours(UTCDate.getHours(), UTCDate.getMinutes(), UTCDate.getSeconds(), UTCDate.getMilliseconds());
    return this.getTime();
}
adhg
  • 10,437
  • 12
  • 58
  • 94
Walf
  • 8,535
  • 2
  • 44
  • 59