Convert UTC Epoch to local date

后端 未结 16 1504
佛祖请我去吃肉
佛祖请我去吃肉 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:09

    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.

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

    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.

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

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

    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
    
    0 讨论(0)
提交回复
热议问题