开发者

Javascript convert seconds to a date object

How can I convert seconds into 开发者_StackOverflow社区a datetime object in javascript.

Examples:

1.3308313703571

1.6324722385401

This is from a series of points and when they occurred. I understand 1.23323 more then seconds, but I can not change the value, being pulled from an api.


You can try like this:

function toDateTime(secs) {
    var t = new Date(1970, 0, 1); // Epoch
    t.setSeconds(secs);
    return t;
}

Info on epoch date.


You can pass unix timestamp milliseconds as an argument to the Date constructor:

const secs = 30;
const output = new Date(secs * 1000);

console.log(output);


@UVM's answer is helpful, but slightly incomplete if you're dealing with timezones (i.e. UTC vs local time). With timezones, start with UTC using Date.UTC and Date.setUTCSeconds to get a true UTC date and time.

function toDateTime(secs) {
    var t = new Date(Date.UTC(1970, 0, 1)); // Epoch
    t.setUTCSeconds(secs);
    return t;
}

You can then use a library like Moment to convert/format it to a local timezone.


your example values have a decimal.. looking like you are trying to convert 1.something seconds into a date..

Meanwhile check this example here on the correct seconds to date conversion.. you could view their js sources.


The question seems to have already been answered but this may be helpful for those attempting to do something similar to ruby's Time.at() method.

function formatDateTime(input){
       var epoch = new Date(0);
       epoch.setSeconds(parseInt(input));
       var date = epoch.toISOString();
       date = date.replace('T', ' ');
       return date.split('.')[0].split(' ')[0] + ' ' + epoch.toLocaleTimeString().split(' ')[0];
};


I dunno how it be 10 years ago, but now it can solve just doing next:

let sec = 1628618888939
let time = new Date(sec)
let normalDate = new Date(sec).toLocaleString('en-GB',{timeZone:'UTC'})
time: "Tue Aug 10 2021 21:08:08 GMT+0300 (Eastern European Summer Time)"
normalDate: "10/08/2021, 18:08:08"

If in the future u will have problems like this, I can advise read about functions that relate to your question, and solution will come.

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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜