Check if event is in future - Yup validation

Viewed 448

I'm currenlty working on yup validation for a page in project. I'm stuck on the following: User chooses date, timezone and specific time of the event (he can choose times from 00:00 to 23:45 every fifteen minutes). Now, I need to validate if chosen time is in the future. I am really confused: should I first convert current moment to users chosen timezone, or convert user's moment to local timezone, or something else. Here's what I did first when I was careless about the timezone:

[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)
      }),

But then I realised that I didn't take into account chosen timezone. Start time here represents number of minutes from 00:00 to chosen time, for example if user chooses 00:15, startTime will be 15. Thanks in advance.

1 Answers

You need to compare - the current time (at the point of submission) with the user's selected/entered date and startTime both in the user's selected zone.


// 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;

Related