Source

tools/hooks/useTimeCheck.ts

import {zonedTimeToUtc} from 'date-fns-tz'
import {isAfter, isBefore, isValid} from 'date-fns'

type TimeCheckReturn = {
    before: boolean
    after: boolean
}

/**
 * Custom hook for checking whether a provided time occurs
 * before or after 'now'.
 *
 * This hook is purely to support consistency in
 * {@link DisplayWhen}'s use of hooks.
 *
 * This hook does not validation its props or do any other
 * developer-friendly checking; it is intended to be used only
 * by the {@link DisplayWhen} component.
 *
 * We strongly recommend the [date-fns](https://date-fns.org/)
 * library for doing time and date comparisons.
 * Do **NOT** use this hook unless you **REALLY** know what
 * you're doing.
 *
 * @category Hooks
 */
export function useTimeCheck(time: string) : TimeCheckReturn {
    let before = false
    let after = false

    // If time is blank, return false for everything
    if (!time) return {before, after}

    try {
        let convertedDate = zonedTimeToUtc(time, '+10')
        if (!isValid(convertedDate)) {
            //TODO: Do we throw exceptions or return "it errored" logic values to the developer?
            throw new DOMException("`time` value provided to useTimeCheck is not a valid date.")
        }

        // Determine if current time is before or after the provided time
        before = isBefore(Date.now(), convertedDate)
        after = isAfter(Date.now(), convertedDate)

    } catch (err) {
        //TODO: Richer error handling
        console.log(err)
        before = false
        after = false
    }

    return {before, after}
}