如何在JavaScript中获得当前时间并在时间选择器中使用它?
我尝试了var x = Date(),得到:
2012年5月15日星期二05:45:40 GMT-0500
但我只需要现在的时间,比如05:45
我怎么把它赋值给变量呢?
如何在JavaScript中获得当前时间并在时间选择器中使用它?
我尝试了var x = Date(),得到:
2012年5月15日星期二05:45:40 GMT-0500
但我只需要现在的时间,比如05:45
我怎么把它赋值给变量呢?
当前回答
function getCurrentTime(){
var date = new Date();
var hh = date.getHours();
var mm = date.getMinutes();
hh = hh < 10 ? '0'+hh : hh;
mm = mm < 10 ? '0'+mm : mm;
curr_time = hh+':'+mm;
return curr_time;
}
其他回答
赋值给变量并显示。
time = new Date();
var hh = time.getHours();
var mm = time.getMinutes();
var ss = time.getSeconds()
document.getElementById("time").value = hh + ":" + mm + ":" + ss;
看看这些Date方法…
更大字符串- https://开发者.mozilla.org/en- us/web /javascrips/web/javascript/javascript / global_objects/date/愚蠢的字符串 totime弦- https://开发者.mozllla.org/en - us/docs/web/javascrips/web/javascript/com// global_objects/date/totimeststststststg
getTime() {
let today = new Date();
let h = today.getHours();
let m = today.getMinutes();
let s = today.getSeconds();
h = h < 10 ? "0" + h : h;
m = m < 10 ? "0" + m : m;
s = s < 10 ? "0" + s : s;
let time = h + ":" + m + ":" + s;
return time;
},
在ES6中一个简单的方法是这样做的,在你要求的格式(hh:mm):
const goodTime = ' ${new Date().getHours()}:${new Date().getMinutes()} '; console.log(因着);
(显然,控制台日志记录不是解决方案的一部分)
function getCurrentTime(){
var date = new Date();
var hh = date.getHours();
var mm = date.getMinutes();
hh = hh < 10 ? '0'+hh : hh;
mm = mm < 10 ? '0'+mm : mm;
curr_time = hh+':'+mm;
return curr_time;
}