Convert UTC Epoch to local date

后端 未结 16 1505
佛祖请我去吃肉
佛祖请我去吃肉 2020-11-22 10:10

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 epoc

相关标签:
16条回答
  • 2020-11-22 11:02

    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);
    
    0 讨论(0)
  • 2020-11-22 11:06

    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

    0 讨论(0)
  • 2020-11-22 11:07

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

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

    0 讨论(0)
  • 2020-11-22 11:08

    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)
    
    0 讨论(0)
  • 2020-11-22 11:08

    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).

    0 讨论(0)
  • 2020-11-22 11:09

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

    new Date(1394104654000)
    > Thu Mar 06 2014 06:17:34 GMT-0500 (EST)
    
    0 讨论(0)
提交回复
热议问题