如何在 Javascript 中格式化时间戳以在图形中显示?UTC 很好
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2315408/
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
How do I format a timestamp in Javascript to display it in graphs? UTC is fine
提问by rmk
Basically, I receive raw timestamps and I need to format them into HH:MM:SS format.
基本上,我收到原始时间戳,我需要将它们格式化为 HH:MM:SS 格式。
回答by harto
Here's a function that provides flexible formatting of a date in UTC. It accepts a format string similar to that of Java's SimpleDateFormat:
这是一个提供灵活的UTC日期格式的函数。它接受类似于 Java 的 SimpleDateFormat 的格式字符串:
function formatDate(date, fmt) {
function pad(value) {
return (value.toString().length < 2) ? '0' + value : value;
}
return fmt.replace(/%([a-zA-Z])/g, function (_, fmtCode) {
switch (fmtCode) {
case 'Y':
return date.getUTCFullYear();
case 'M':
return pad(date.getUTCMonth() + 1);
case 'd':
return pad(date.getUTCDate());
case 'H':
return pad(date.getUTCHours());
case 'm':
return pad(date.getUTCMinutes());
case 's':
return pad(date.getUTCSeconds());
default:
throw new Error('Unsupported format code: ' + fmtCode);
}
});
}
You could use it like this:
你可以这样使用它:
formatDate(new Date(timestamp), '%H:%m:%s');
回答by JonathanK
I'll go with the assumption that you mean Unix timestamps:
我会假设你的意思是 Unix 时间戳:
var formatTime = function(unixTimestamp) {
var dt = new Date(unixTimestamp * 1000);
var hours = dt.getHours();
var minutes = dt.getMinutes();
var seconds = dt.getSeconds();
// the above dt.get...() functions return a single digit
// so I prepend the zero here when needed
if (hours < 10)
hours = '0' + hours;
if (minutes < 10)
minutes = '0' + minutes;
if (seconds < 10)
seconds = '0' + seconds;
return hours + ":" + minutes + ":" + seconds;
}
var formattedTime = formatTime(1266272460);
document.write(formattedTime);
回答by kaelle
This will display the current time in the format you asked for (HH:MM:SS)
这将以您要求的格式显示当前时间 ( HH:MM:SS)
function dostuff()
{
var item = new Date();
alert(item.toTimeString());
}

