rmk*_*rmk 16 javascript jquery
基本上,我收到原始时间戳,我需要将它们格式化为HH:MM:SS格式.
har*_*rto 31
这是一个以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);
}
});
}
Run Code Online (Sandbox Code Playgroud)
你可以像这样使用它:
formatDate(new Date(timestamp), '%H:%m:%s');
Run Code Online (Sandbox Code Playgroud)
Jon*_*anK 30
我会假设您的意思是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);
Run Code Online (Sandbox Code Playgroud)
这将以您要求的格式显示当前时间(HH:MM:SS)
function dostuff()
{
var item = new Date();
alert(item.toTimeString());
}
Run Code Online (Sandbox Code Playgroud)