Convert UTC Epoch to local date

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

提交回复
热议问题