如何在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 now = new Date().toLocaleTimeString();
console.log(now)
这里还有一种没有提到的字符串操作方法。
var now = new Date()
console.log(now.toString().substr(16,8))
其他回答
var today = new Date(); //gets current date and time
var hour = today.getHours();
var minute = today.getMinutes();
var second = today.getSeconds();
Try
new Date().toLocaleTimeString().replace("/.*(\d{2}:\d{2}:\d{2}).*/", "$1");
Or
new Date().toTimeString().split(" ")[0];
这对我来说很有效,但这取决于你点击Date()时得到的结果:
Date().slice(16,-12)
在ES6中一个简单的方法是这样做的,在你要求的格式(hh:mm):
const goodTime = ' ${new Date().getHours()}:${new Date().getMinutes()} '; console.log(因着);
(显然,控制台日志记录不是解决方案的一部分)
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;