如何在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;
}

其他回答

您可以简单地使用这些方法。

console.log(新日期()。toLocaleTimeString([],{小时:'2-digit',分钟:'2-digit',小时12:false})); console.log(新日期()。toLocaleTimeString([],{小时:'2-digit',分钟:'2-digit'}));

试试这个:

var date = new Date();
var hour = date.getHours();
var min = date.getMinutes();

在ES6中一个简单的方法是这样做的,在你要求的格式(hh:mm):

const goodTime = ' ${new Date().getHours()}:${new Date().getMinutes()} '; console.log(因着);

(显然,控制台日志记录不是解决方案的一部分)

赋值给变量并显示。

time = new Date();

var hh = time.getHours();
var mm = time.getMinutes();
var ss = time.getSeconds() 

document.getElementById("time").value = hh + ":" + mm + ":" + ss;

const date = date ().slice(16,21); console.log(日期);