如何在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
我怎么把它赋值给变量呢?
当前回答
看看这些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
其他回答
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;
以下是我的做法:(希望能帮助到别人) 我正在做的是验证用户在HTML时间输入中输入的时间不是过去:
let inputTime = value; // from time input in html (06:29)
const splittedInputTime = inputTime.split(':');
let currentDate = new Date();
currentDate.setHours(splittedInputTime[0]);
currentDate.setMinutes(splittedInputTime[1]);
const finalInputTime = currentDate.toTimeString().split(" ")[0];
const currentTime = new Date().toTimeString().split(" ")[0];
// Returns a boolean (true/ false)
let validTime = finalInputTime >= currentTime;
看看这些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
这对我来说很有效,但这取决于你点击Date()时得到的结果:
Date().slice(16,-12)