时间选择器将最小时间增加 1 小时 [英] timepicker increment min time by 1 hour

查看:47
本文介绍了时间选择器将最小时间增加 1 小时的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的应用中,用户可以在早上 6:00 到晚上 8:00 之间进行预约.我正在使用 timepicker 来做到这一点.我正在设置 minTime: 6:00 AMmaxTime : 8:00 PM.这有效,但当用户当前时间在早上 6 点到晚上 7 点之间时,我实际上希望将 minTime 增加 1 小时.如果是早上 6 点 01 分,则用户不应选择早上 6 点,而应改为建议早上 7 点.晚上 7 点 01 分,剩下的唯一挑选时间应该是晚上 8 点.

In my app, users can book appointments from 6:00 AM to 8:00 PM. I'm using timepicker to do that. I'm setting minTime: 6:00 AM and maxTime : 8:00 PM. This works but I would actually like to increment minTime by 1hour when the user current time is between 6AM and 7PM. If it is 6:01 AM, the user should not be able to pick 6AM but should be suggested 7AM instead. At 7:01PM, the only time left to pick should be 8PM.

//current date
var dateToday = new Date(); 
//get time in US format
//console.log(dateToday.toLocaleTimeString('en-US'));
var timeNow = dateToday.toLocaleTimeString('en-US');
// expected output: 1:15:30 AM
//get time in 12H format
//console.log(dateToday.toLocaleTimeString('it-IT'));
// expected output: 01:15:30

if(timeNow > '6:00:00 AM'&& timeNow < '8:00:00 PM'){
  var minTime = timeNow + 1:00:00;
}else{
  var mintime = '6:00am';
}

//time picker
$(function () {
$('.timepicker').timepicker({
timeFormat: 'h:mm p',
interval: 60,
minTime: minTime,
maxTime: '8:00pm',
dynamic: false,
dropdown: true,
scrollbar: true

});
});

推荐答案

使用 new Date().getHours() 获取小时数.您不能将 <> 用于字符串.这意味着您需要将它们转换为数字.由于您只需要比较小时,那么只需获取小时并进行比较即可.像下面这样:

Use new Date().getHours() to get the hours. You cant use < and > to strings. Which means you need to convert them to numbers. Since you only need the hour to compare then just get the hours and compare it. Like the following:

var today = new Date();
var hr = today.getHours();
var min = today.getMinutes();
var time = hr >= 12 ? "pm" : "am";

if(hr > 6 && hr < 8) {
  minTime = hr + 1;
}
else {
  minTime = hr
}
minTime = `${minTime > 12 ? minTime - 12 : minTime}:${min}${time}`

//time picker
$(function () {
$('.timepicker').timepicker({
timeFormat: 'h:mm p',
interval: 60,
minTime: minTime,
maxTime: '8:00pm',
dynamic: false,
dropdown: true,
scrollbar: true
});

这篇关于时间选择器将最小时间增加 1 小时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆