如何从日期对象中获取 hh:mm:ss?
var d = new Date(); // for now
datetext = d.getHours()+":"+d.getMinutes()+":"+d.getSeconds();
有时候我会得到以下结果:
12:10:1
应该是哪一个。12:10:01
我假设这也会发生在小时和分钟上。
因此,我需要这个。
01:01:01
不是这样的 1:1:1
如何从日期对象中获取 hh:mm:ss?
var d = new Date(); // for now
datetext = d.getHours()+":"+d.getMinutes()+":"+d.getSeconds();
有时候我会得到以下结果:
12:10:1
应该是哪一个。12:10:01
我假设这也会发生在小时和分钟上。
因此,我需要这个。
01:01:01
不是这样的 1:1:1
解决方案 - (简短版)
datetext = d.toTimeString().split(' ')[0]
说明:
toTimeString
返回完整的时间。
我们通过空格将其分割以仅获取时间组件,然后取第一个有用的值。 :)
完整流程:
d = new Date();
// d is "Sun Oct 13 2013 20:32:01 GMT+0530 (India Standard Time)"
datetext = d.toTimeString();
// datestring is "20:32:01 GMT+0530 (India Standard Time)"
// Split with ' ' and we get: ["20:32:01", "GMT+0530", "(India", "Standard", "Time)"]
// Take the first value from array :)
datetext = datetext.split(' ')[0];
注意:这不需要您包含任何外部文件或库,因此执行所需时间将更快。
jsfiddle
中,并添加了类型安全的注释,请务必查看fiddle。$(document).ready(function(){
var d = new Date();
var formatted_time = time_format(d);
$('#yourTimeField').text(formatted_time);
});
将以下两个方法添加到您的脚本中(您也可以像jsfiddle代码片段中一样将其粘贴到单个文件中):
function time_format(d) {
hours = format_two_digits(d.getHours());
minutes = format_two_digits(d.getMinutes());
seconds = format_two_digits(d.getSeconds());
return hours + ":" + minutes + ":" + seconds;
}
function format_two_digits(n) {
return n < 10 ? '0' + n : n;
}
就这样了 :) 希望有所帮助 :)
minutes =
,您正在设置全局命名空间内的分钟数,我认为 var minutes =
更好(或在 ES6 中使用 const minutes =
)。 - Tomáš Kafka