如何在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
我怎么把它赋值给变量呢?
当前回答
简单的函数,以获得日期和时间分离,并与时间和日期HTML输入兼容的格式
function formatDate(date) {
var d = new Date(date),
month = '' + (d.getMonth() + 1),
day = '' + d.getDate(),
year = d.getFullYear();
if (month.length < 2) month = '0' + month;
if (day.length < 2) day = '0' + day;
return [year, month, day].join('-');
}
function formatTime(date) {
var hours = new Date().getHours() > 9 ? new Date().getHours() : '0' + new Date().getHours()
var minutes = new Date().getMinutes() > 9 ? new Date().getMinutes() : '0' + new Date().getMinutes()
return hours + ':' + minutes
}
其他回答
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;
}
看看这些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
在ES6中一个简单的方法是这样做的,在你要求的格式(hh:mm):
const goodTime = ' ${new Date().getHours()}:${new Date().getMinutes()} '; console.log(因着);
(显然,控制台日志记录不是解决方案的一部分)
Try
new Date().toLocaleTimeString().replace("/.*(\d{2}:\d{2}:\d{2}).*/", "$1");
Or
new Date().toTimeString().split(" ")[0];
你可以这样做。
const date = new date (); const time = date.toTimeString()。分割(' ')[0].split(“:”); Console.log (time[0] + ':' + time[1])