date-fns#isValid JavaScript Examples

The following examples show how to use date-fns#isValid. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: index.js    From ftx-cli with MIT License 6 votes vote down vote up
function calculateMillisecondsUntilDate(date) {
  const currentDate = new Date();
  const scheduleDate = parseISO(date);

  if (!isValid(scheduleDate)) {
    return null;
  }

  if (isBefore(scheduleDate, currentDate)) {
    return null;
  }

  return differenceInMilliseconds(scheduleDate, currentDate);
}
Example #2
Source File: DateTimeCell.js    From dm2 with Apache License 2.0 6 votes vote down vote up
DateTimeCell = (column) => {
  const date = new Date(column.value);
  const dateFormat = "MMM dd yyyy, HH:mm:ss";

  return column.value ? (
    <div style={{ whiteSpace: "nowrap" }}>
      {isValid(date) ? format(date, dateFormat) : ""}
    </div>
  ) : (
    ""
  );
}
Example #3
Source File: DateTime.js    From rate-repository-api with MIT License 5 votes vote down vote up
isValidDateTime = value => {
  const isSerializable =
    isDate(value) || typeof value === 'string' || typeof value === 'number';

  return isSerializable ? isValid(new Date(value)) : false;
}
Example #4
Source File: Date.js    From dm2 with Apache License 2.0 5 votes vote down vote up
DateTimeInput = observer(({ value, range, time, onChange }) => {
  const onValueChange = React.useCallback(
    (selectedDate) => {
      let value;

      if (Array.isArray(selectedDate)) {
        const [min, max] = selectedDate
          .map((d) => d ? new Date(d) : null)
          .map((d) => (isValid(d) ? d.toISOString() : null));

        value = { min, max };
      } else {
        value = selectedDate?.toISOString();
      }

      onChange(value);
    },
    [onChange],
  );

  const dateValue = React.useMemo(() => {
    if (range) {
      const { min, max } = value ?? {};

      return [min, max]
        .map((d) => (d === null ? undefined : d))
        .map((d) => new Date(d))
        .map((d) => (isValid(d) ? d : undefined));
    } else {
      const date = new Date(value === null ? undefined : value);

      return isValid(date) ? date : undefined;
    }
  }, [range, value]);

  return (
    <DatePicker
      size="small"
      value={dateValue}
      selectRange={range}
      showTime={time === true}
      onChange={onValueChange}
    />
  );
})
Example #5
Source File: useDateInput.js    From react-nice-dates with MIT License 5 votes vote down vote up
export default function useDateInput({
  date: selectedDate,
  format: receivedFormatString,
  locale,
  minimumDate,
  maximumDate,
  onDateChange,
  validate
}) {
  const formatString = receivedFormatString || locale.formatLong.date({ width: 'short' })

  const formatDate = date => format(date, formatString, { locale })
  const parseDate = dateString => parse(dateString, formatString, selectedDate || new Date())
  const isValidAndSelectable = date =>
    isValid(date) && isSelectable(date, { minimumDate, maximumDate }) && (!validate || validate(date))

  const [value, setValue] = useState(isValidAndSelectable(selectedDate) ? formatDate(selectedDate) : '')
  const [focused, setFocused] = useState(false)

  const handleFocus = () => {
    setFocused(true)
  }

  const handleChange = event => {
    const newValue = event.target.value
    const parsedDate = parseDate(newValue)
    setValue(newValue)

    if (isValidAndSelectable(parsedDate)) {
      onDateChange(parsedDate)
    }
  }

  const handleBlur = () => {
    if (value) {
      const parsedDate = parseDate(value)

      if (isValidAndSelectable(parsedDate)) {
        setValue(formatDate(parsedDate))
      } else if (isValidAndSelectable(selectedDate)) {
        setValue(formatDate(selectedDate))
      } else {
        setValue('')
      }
    } else if (selectedDate) {
      onDateChange(null)
    }

    setFocused(false)
  }

  useEffect(() => {
    if (!focused) {
      setValue(isValidAndSelectable(selectedDate) ? formatDate(selectedDate) : '')
    }
  }, [selectedDate, focused]) // eslint-disable-line react-hooks/exhaustive-deps

  return {
    onFocus: handleFocus,
    onChange: handleChange,
    onBlur: handleBlur,
    placeholder: formatString.toLowerCase(),
    type: 'text',
    value
  }
}
Example #6
Source File: DatePicker.js    From dm2 with Apache License 2.0 4 votes vote down vote up
DatePicker = ({
  size,
  value,
  selectRange = false,
  showTime = false,
  dateFormat = "MM.dd.yyyy",
  timeFormat = "HH:mm",
  onChange,
}) => {
  const finalFormat = showTime ? `${dateFormat} ${timeFormat}` : dateFormat;

  /**@type {import("react").RefObject<DP>} */
  const datepickerRef = useRef();

  const dropdownRef = useRef();

  const formatDate = (date) => {
    if (!isDefined(date)) return "";

    const parsedDate = new Date(date === null ? Date.now() : date);

    if (isValid(parsedDate)) {
      return format(parsedDate, finalFormat);
    }

    return "";
  };

  const [initialStartDate, initialEndDate] = selectRange
    ? value
    : [].concat(value);

  const [realStartDate, setRealStartDate] = useState(initialStartDate ?? null);
  const [realEndDate, setRealEndDate] = useState(initialEndDate ?? null);

  const [startDate, setStartDate] = useState(formatDate(realStartDate));
  const [endDate, setEndDate] = useState(formatDate(realEndDate));

  const updateDate = (date, dateSetter, realDateSetter) => {
    if (date.length > finalFormat.length) return;

    dateSetter?.(date);

    if (isDefined(date) && isMatch(date, finalFormat) && date.length === finalFormat.length) {
      const realDate = new Date(date || null);

      if (isValid(realDate)) realDateSetter?.(realDate);
    }
  };

  const dateRange = useMemo(
    () =>
      selectRange
        ? {
          startDate: realStartDate,
          endDate: realEndDate,
        }
        : {},
    [selectRange, realStartDate, realEndDate],
  );

  useEffect(() => {
    if (isValid(realStartDate)) setStartDate(formatDate(realStartDate));
  }, [realStartDate]);

  useEffect(() => {
    if (isValid(realEndDate)) setEndDate(formatDate(realEndDate));
  }, [realEndDate]);

  useEffect(() => {
    if (selectRange) {
      onChange?.([realStartDate, realEndDate]);
    } else if (realStartDate) {
      onChange?.(realStartDate);
    }
  }, [realStartDate, realEndDate]);

  const onChangeHandler = useCallback((date) => {
    if (realStartDate !== null && realEndDate === null && selectRange) {
      setRealEndDate(date);
      dropdownRef.current?.close();
    } else {
      setRealStartDate(date);
      if (selectRange) {
        setRealEndDate(null);
      } else {
        dropdownRef.current?.close();
      }
    }
  });

  return (
    <Block name="datepicker">
      <Dropdown.Trigger
        ref={dropdownRef}
        toggle={false}
        content={(
          <DP
            {...dateRange}
            ref={datepickerRef}
            selected={realStartDate}
            onChange={(date) => onChangeHandler(date)}
            onSelect={(date) => onChangeHandler(date)}
            monthsShown={2}
            selectsRange={selectRange}
            showTimeSelect={showTime}
            inline
          />
        )}
      >
        <Elem name="output" mod={{ range: selectRange }}>
          <Input
            size={size}
            value={startDate || ""}
            onChange={(e) =>
              updateDate(e.target.value, setStartDate, setRealStartDate)
            }
          />
          {selectRange && (
            <>
              <Elem name="separator">
                <Icon icon={FaExchangeAlt} />
              </Elem>
              <Input
                size={size}
                value={endDate || ""}
                onChange={(e) =>
                  updateDate(e.target.value, setEndDate, setRealEndDate)
                }
              />
            </>
          )}
        </Elem>
      </Dropdown.Trigger>
    </Block>
  );
}
Example #7
Source File: dateFns.js    From the-eye-knows-the-garbage with MIT License 4 votes vote down vote up
generateConfig = {
  // get
  getNow: function getNow() {
    return new Date();
  },
  getWeekDay: function getWeekDay(date) {
    return getDay(date);
  },
  getYear: function getYear(date) {
    return _getYear(date);
  },
  getMonth: function getMonth(date) {
    return _getMonth(date);
  },
  getDate: function getDate(date) {
    return _getDate(date);
  },
  getHour: function getHour(date) {
    return getHours(date);
  },
  getMinute: function getMinute(date) {
    return getMinutes(date);
  },
  getSecond: function getSecond(date) {
    return getSeconds(date);
  },
  // set
  addYear: function addYear(date, diff) {
    return addYears(date, diff);
  },
  addMonth: function addMonth(date, diff) {
    return addMonths(date, diff);
  },
  addDate: function addDate(date, diff) {
    return addDays(date, diff);
  },
  setYear: function setYear(date, year) {
    return _setYear(date, year);
  },
  setMonth: function setMonth(date, month) {
    return _setMonth(date, month);
  },
  setDate: function setDate(date, num) {
    return _setDate(date, num);
  },
  setHour: function setHour(date, hour) {
    return setHours(date, hour);
  },
  setMinute: function setMinute(date, minute) {
    return setMinutes(date, minute);
  },
  setSecond: function setSecond(date, second) {
    return setSeconds(date, second);
  },
  // Compare
  isAfter: function isAfter(date1, date2) {
    return _isAfter(date1, date2);
  },
  isValidate: function isValidate(date) {
    return isValid(date);
  },
  locale: {
    getWeekFirstDay: function getWeekFirstDay(locale) {
      var clone = Locale[dealLocal(locale)];
      return clone.options.weekStartsOn;
    },
    getWeek: function getWeek(locale, date) {
      return _getWeek(date, {
        locale: Locale[dealLocal(locale)]
      });
    },
    format: function format(locale, date, _format) {
      if (!isValid(date)) {
        return null;
      }

      return formatDate(date, _format, {
        locale: Locale[dealLocal(locale)]
      });
    },
    parse: function parse(locale, text, formats) {
      for (var i = 0; i < formats.length; i += 1) {
        var format = formats[i];
        var formatText = text;
        var date = parseDate(formatText, format, new Date(), {
          locale: Locale[dealLocal(locale)]
        });

        if (isValid(date)) {
          return date;
        }
      }

      return null;
    }
  }
}