strftime.js (strftime github) 是最好的时间格式化库之一。它非常轻 - 30KB - 并且有效。使用它,您可以在一行代码中轻松将秒转换为时间,主要依赖于原生 Date 类。
创建新日期时,每个可选参数的位置如下:
new Date(year, month, day, hours, minutes, seconds, milliseconds);
因此,如果您初始化一个新的 Date 并将所有参数设置为零直到秒,您将得到:
var seconds = 150;
var date = new Date(0,0,0,0,0,seconds);
=> Sun Dec 31 1899 00:02:30 GMT-0500 (EST)
您可以看到 150 秒是 2 分 30 秒,如创建日期所示。然后使用 strftime 格式(“%M:%S”代表“MM:SS”),它将输出您的分钟字符串。
var mm_ss_str = strftime("%M:%S", date);
=> "02:30"
在一行中,它看起来像:
var mm_ss_str = strftime('%M:%S', new Date(0,0,0,0,0,seconds));
=> "02:30"
另外,这将允许您根据秒数互换支持 HH:MM:SS 和 MM:SS。例如:
# Less than an Hour (seconds < 3600)
var seconds = 2435;
strftime((seconds >= 3600 ? '%H:%M:%S' : '%M:%S'), new Date(0,0,0,0,0,seconds));
=> "40:35"
# More than an Hour (seconds >= 3600)
var seconds = 10050;
strftime((seconds >= 3600 ? '%H:%M:%S' : '%M:%S'), new Date(0,0,0,0,0,seconds));
=> "02:47:30"
当然,如果您希望时间字符串具有或多或少的语义,您可以简单地将您想要的任何格式传递给 strftime。
var format = 'Honey, you said you\'d be read in %S seconds %M minutes ago!';
strftime(format, new Date(0,0,0,0,0,1210));
=> "Honey, you said you'd be read in 10 seconds 20 minutes ago!"