1

I'm basically trying to get the hours, minutes, and seconds of a date in javascript to read like this: '123456'. I am doing this with the following code:

var date;
date = new Date();
var time = date.getUTCHours() + date.getUTCMinutes() + date.getUTCSeconds();

Only problem is when I add them together, I keep getting the sum, not a nice line of 6 numbers like I want.

Any Suggestions?

4

3 回答 3

2
var time = '' + date.getUTCHours() + date.getUTCMinutes() + date.getUTCSeconds();

编辑:要考虑零填充,您可以执行以下操作:

function format(x){
    if (x < 10) return '0' + x;
    return x;
}

var date;
date = new Date();
var time = '' + format(date.getUTCHours()) + format(date.getUTCMinutes()) + format(date.getUTCSeconds());
于 2013-07-24T16:52:58.287 回答
2

将数值转换为字符串:

var date;
date = new Date();
var time = date.getUTCHours().toString() + date.getUTCMinutes().toString() + date.getUTCSeconds().toString();

如果您希望它始终为 6 个字符长,则需要填充小于 10 的值。例如:

var hours = date.getUTCHours();
if (hours < 10)
     hours = '0' + hours.toString();
else hours = hours.toString();

var mins = date.getUTCMinutes();
if (mins < 10)
     mins = '0' + mins.toString();
else mins = mins.toString();

var secs = date.getUTCSeconds();
if (secs < 10)
     secs = '0' + secs.toString();
else secs = secs.toString();

var time = hours + mins + secs;
于 2013-07-24T16:51:13.683 回答
0

发生这种情况是因为这些函数返回一个 Integer 类型。如果您想自己添加数字,请尝试使用 toString() 将每个变量转换为字符串

于 2013-07-24T16:54:51.693 回答