如何在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
我怎么把它赋值给变量呢?
当前回答
你的意思是:
var d = new Date();
var curr_hour = d.getHours();
var curr_min = d.getMinutes();
其他回答
这对我来说很有效,但这取决于你点击Date()时得到的结果:
Date().slice(16,-12)
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;
}
var hours = date.getHours();
var minutes = date.getMinutes();
var ampm = hours >= 12 ? 'pm' : 'am';
hours = hours % 12;
hours = hours ? hours : 12; // the hour '0' should be '12'
minutes = minutes < 10 ? '0'+minutes : minutes;
var strTime = hours + ':' + minutes + ' ' + ampm;
console.log(strTime);
$scope.time = strTime;
date.setDate(date.getDate()+1);
month = '' + (date.getMonth() + 1),
day = '' + date.getDate(1),
year = date.getFullYear();
if (month.length < 2) month = '0' + month;
if (day.length < 2) day = '0' + day;
var tomorrow = [year, month, day].join('-');
$scope.tomorrow = tomorrow;
在ES6中一个简单的方法是这样做的,在你要求的格式(hh:mm):
const goodTime = ' ${new Date().getHours()}:${new Date().getMinutes()} '; console.log(因着);
(显然,控制台日志记录不是解决方案的一部分)
试试这个
new Date().toTimeString().slice(0, 8);
or
new Date().toTimeString().split(" ")[0];
它应该会起作用。