reactjs - 检查事件是否在未来 - 是的验证
问题描述
我正在为项目中的页面进行 yup 验证。我坚持以下几点:用户选择事件的日期、时区和特定时间(他可以选择每十五分钟从 00:00 到 23:45 的时间)。现在,我需要验证选择的时间是否在未来。我真的很困惑:我应该首先将当前时刻转换为用户选择的时区,还是将用户的时刻转换为本地时区,或者其他什么。这是我对时区粗心时首先做的事情:
[keys.startTime]: yup
.number()
.required(errors.required)
.when(['date'], (date, schema: any) => {
const currentTimeInMinutes = moment().hours() * 60 + moment().minutes()
if (
moment(date).date() === moment().date() &&
moment(date).month() === moment().month() &&
moment(date).year() === moment().year()
)
return schema.min(currentTimeInMinutes, errors.pastTime)
}),
但后来我意识到我没有考虑到选择的时区。这里的开始时间表示从 00:00 到所选时间的分钟数,例如如果用户选择 00:15,则 startTime 将为 15。提前致谢。
解决方案
您需要将当前时间(在提交时)与用户选择/输入的时间date
以及startTime
用户选择的区域进行比较。
// Calculate the offset of the timezone that user selected from UTC
const utcOffset = '+05:30'; // Example of a time zone in India
const currentTime = moment().utcOffset(utcOffset);
const userSelectionTime =
moment(date).utcOffset(utcOffset)
.startOf('day')
.add(startTime, 'minutes');
/*
* Check if the difference between the `userSelectionTime` and the `currentTime`
* is greater than 0 minutes (you can change this as per your requirements)
*/
const selectionIsValid = userSelectionTime.diff(currentTime, 'minutes') > 0;
推荐阅读
- vue.js - 动态实例化的 Vue 组件如何被缓存?
- html - Magento HTML问题 - 侧栏出现在页面内容下方
- git - Git 将已存在的文件显示为新文件
- react-native - 如何在 defaultNavigationOptions 上添加订阅
- arrays - 在 pymongo 的 mongo 文档中返回整个嵌套数组
- python-3.x - 使用 Tensorflow 对象检测 API 的 mAP
- unity3d - ARcore Camera 纹理只能从 Unity Editor 获得
- dataframe - 重命名多索引元组熊猫数据框
- javascript - 使用什么代替 ActiveXObject 使其跨浏览器兼容
- sql - 按销售人员计算销售额