首页 > 解决方案 > 检查事件是否在未来 - 是的验证

问题描述

我正在为项目中的页面进行 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。提前致谢。

标签: reactjsvalidationyup

解决方案


您需要将当前时间(在提交时)与用户选择/输入的时间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;


推荐阅读