Javascript Javascript将秒转换为日期对象
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4611754/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Javascript convert seconds to a date object
提问by jhanifen
How can I convert seconds into a datetime object in javascript.
如何在 javascript 中将秒转换为日期时间对象。
Examples:
例子:
1.3308313703571
1.3308313703571
1.6324722385401
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.
这是从一系列的观点和它们发生的时间来看的。我理解 1.23323 多于几秒,但我无法更改该值,因为它是从 api 中提取的。
回答by UVM
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.
有关纪元日期的信息。
回答by Klesun
回答by run.revelations
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.
这个问题似乎已经得到了回答,但这可能对那些试图做类似于 ruby 的 Time.at() 方法的人有所帮助。
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];
};
回答by Harish
your example values have a decimal.. looking like you are trying to convert 1.something seconds into a date..
您的示例值有一个小数.. 看起来您正在尝试将 1.something 秒转换为日期..
Meanwhile check this example hereon the correct seconds to date conversion.. you could view their js sources.
同时在此处查看此示例以了解正确的秒数到日期转换。您可以查看他们的 js 源代码。
回答by Imagine Breaker
/**
DateTime
-------
Author: Jamal BOUIZEM
Date: 20/02/2015
Version: 1.0.0
*/
var DateTime = (function(){
return {
instance: function(spec){
var that = {
h: spec.h || 0,
m: spec.m || 0,
s: spec.s || 0
};
var d = new Date();
var str = "";
function __init__(h, m, s)
{
that.h = h;
that.m = m;
that.s = s;
d.setHours(that.h);
d.setMinutes(that.m);
d.setSeconds(that.s);
};
that.get = function(){
d.setHours(that.h);
d.setMinutes(that.m);
d.setSeconds(that.s);
return d;
};
that.set = function(h, m, s){
__init__(h, m, s);
};
that.convertSecs = function(){
return (that.h * 3600) + (that.m * 60) + that.s;
};
that.secsToDate = function(seconds){
var ts = seconds % 60;
var tm = (seconds / 60) % 60;
var th = (seconds / 3600) % 60;
return DateTime.instance({ h: parseInt(th), m: parseInt(tm), s: parseInt(ts) });
};
that.add = function(d){
return that.secsToDate(that.convertSecs() + d.convertSecs());
};
that.subtract = function(d){
return that.secsToDate(that.convertSecs() - d.convertSecs());
};
__init__(that.h, that.m, that.s);
return that;
}
}
})();