我正在尝试连接并显示小时,分钟和秒,但它们会像整数一样添加而不是连接。我做错了什么?
var date = new Date();
//return
console.log(
date.getHours()<10 ? "0"+date.getHours() : date.getHours().toString()
+ date.getMinutes()<10 ? "0"+date.getMinutes(): date.getMinutes().toString()
+ date.getSeconds() < 10 ? "0" + date.getSeconds(): date.getSeconds().toString());
我得到一个像13这样的数字,而不是像012208那样的时间
答案 0 :(得分:0)
var date = new Date();
//return
console.log(
(date.getHours()<10 ? "0"+date.getHours() : date.getHours().toString() )
+ (date.getMinutes()<10 ? "0"+date.getMinutes(): date.getMinutes().toString())
+ (date.getSeconds() < 10 ? "0" + date.getSeconds(): date.getSeconds().toString()));
&#13;
在这里。检查括号
答案 1 :(得分:0)
问题在于您在三元运算符中使用的优先级。
console.log((date.getHours()<10 ? "0"+date.getHours() : date.getHours().toString())+ (date.getMinutes()<10 ? "0"+date.getMinutes(): date.getMinutes().toString()) + (date.getSeconds() < 10 ? "0" + date.getSeconds(): date.getSeconds().toString()));
这可以解决您的问题
答案 2 :(得分:0)
试试这个,你没有关闭ternary
运算符
var date = new Date();
//return
var h = date.getHours() < 10 ? "0" + date.getHours() : date.getHours().toString();
var min = date.getMinutes() < 10 ? "0" + date.getMinutes() : date.getMinutes().toString();
var sec = date.getSeconds() < 10 ? "0" + date.getSeconds() : date.getSeconds().toString(); console.log(h +':'+ min +':'+ sec)
答案 3 :(得分:0)
你忘记了括号:
console.log(
(date.getHours() < 10 ? '0' + date.getHours().toString() : date.getHours().toString()) +
(date.getMinutes() < 10 ? '0' + date.getMinutes().toString() : date.getMinutes().toString()) +
(date.getSeconds() < 10 ? '0' + date.getSeconds().toString() : date.getSeconds().toString()) );
答案 4 :(得分:0)
您需要在条件周围添加括号。正如你现在拥有的那样,它正在执行,就好像它是:
function dateStr(date) {
var hoursStr, minutesStr, secondsStr;
if (date.getHours() < 10) {
hoursStr = "0" + date.getHours();
} else {
if (date.getMinutes() < 10) {
minutesStr = "0" + date.getMinutes();
} else {
if ( date.getSeconds() < 10) {
secondsStr = "0" + date.getSeconds();
} else {
secondsStr = date.getSeconds().toString();
}
minutesStr = date.getMinutes().toString() + secondsStr;
}
hoursStr = date.getHours().toString() + minutesStr;
}
return hoursStr;
}
var date = new Date();
// If the hours/minutes/seconds are 10 or more you will get what you want
date.setHours(10);
date.setMinutes(10);
date.setSeconds(10);
console.log(dateStr(date)); // => "101010"
// If the minutes are less than 10, no seconds show
date.setMinutes(5);
console.log(dateStr(date)); // => "1005"
// If the hours are less than 10, no minutes or seconds show
date.setHours(4);
console.log(dateStr(date)); // => "04"
&#13;
通过在条件语句周围添加括号,可以更正操作顺序:
var date = new Date();
console.log(
(date.getHours() < 10 ? "0" + date.getHours() : date.getHours().toString()) +
(date.getMinutes() < 10 ? "0" + date.getMinutes(): date.getMinutes().toString()) +
(date.getSeconds() < 10 ? "0" + date.getSeconds(): date.getSeconds().toString())
);
&#13;