date-fns#isValid TypeScript 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: DatePicker.tsx From symphony-ui-toolkit with Apache License 2.0 | 7 votes |
private computeError(date): ErrorMessages {
const { disabledDays } = this.props;
if (!date) {
return null;
}
if (!isValid(date)) {
return { format: 'The date format is incorrect' };
} else if (matchDayMax(date, disabledDays)) {
return { maxDate: 'Date too far in the future' };
} else if (matchDayMin(date, disabledDays)) {
return { minDate: 'Date too far in the past' };
} else if (matchDay(date, disabledDays)) {
return { disabledDate: 'This date is not available' };
} else {
return null;
}
}
Example #2
Source File: helpers.ts From glide-frontend with GNU General Public License v3.0 | 6 votes |
combineDateAndTime = (date: Date, time: Date) => {
if (!isValid(date) || !isValid(time)) {
return null
}
const dateStr = format(date, 'yyyy-MM-dd')
const timeStr = format(time, 'HH:mm:ss')
return parseISO(`${dateStr}T${timeStr}`).getTime() / 1e3
}
Example #3
Source File: worklogs.ts From tempomat with MIT License | 6 votes |
function parseWhenArg(now: Date, when: string | undefined): Date {
if (when === undefined) return now
if (YESTERDAY_LITERALS.includes(when)) {
const nowAtMidnight = new Date(now)
nowAtMidnight.setHours(0, 0, 0, 0)
return addDays(nowAtMidnight, -1)
}
if (when.match(TODAY_REFERENCE_REGEX)) {
const nowAtMidnight = new Date(now)
nowAtMidnight.setHours(0, 0, 0, 0)
return addDays(nowAtMidnight, parseInt(when.replace(/[^\d+-]/g, '')))
}
const date = fnsParse(when, DATE_FORMAT, new Date())
if (isValid(date)) {
return date
} else {
throw Error(`Cannot parse "${when}" to valid date. Try to use YYYY-MM-DD format. See ${appName} --help for more examples.`)
}
}
Example #4
Source File: timeParser.ts From tempomat with MIT License | 6 votes |
export function toInterval(seconds: number, startTime: string, referenceDate: Date): Interval | null {
if (seconds < 0) return null
const parsedStartTime = fnsParse(startTime, 'HH:mm:ss', referenceDate)
if (isValid(parsedStartTime)) {
const startTime = format(parsedStartTime, 'HH:mm')
const endTime = format(addSeconds(parsedStartTime, seconds), 'HH:mm')
return {
startTime: startTime,
endTime: endTime
}
} else {
return null
}
}
Example #5
Source File: RelativeRangePicker.tsx From gio-design with Apache License 2.0 | 6 votes |
function RelativeRangePicker({ disabledDate, timeRange, onSelect, onCancel, ...rest }: RangePickerProps) {
const defaultDates = parseStartAndEndDate(timeRange ?? 'day:2,1');
const [dates, setDates] = React.useState<[Date, Date]>(defaultDates as [Date, Date]);
const [endDateHidden, setEndDateHidden] = React.useState<boolean>(isYesterday(dates[1]));
const inputDisabled = !isNil(disabledDate);
const handleDisabledDate = (current: Date) =>
disabledDate?.(current) || isAfter(startOfDay(current), endDateHidden ? startOfYesterday() : startOfToday());
const handleOnOK = () => {
onSelect(`day:${differenceInDays(startOfToday(), dates[0]) + 1},${differenceInDays(startOfToday(), dates[1])}`);
};
return (
<InnerRangePanel
data-testid="relative-range-picker"
disableOK={!isValid(dates[0]) || !isValid(dates[1])}
header={<RelativeRangeHeader inputDisabled={inputDisabled} dateRange={dates} onRangeChange={setDates} onModeChange={setEndDateHidden} />}
body={
<RelativeRangeBody
dateRange={dates}
fixedMode={endDateHidden}
disabledDate={handleDisabledDate}
onRangeChange={setDates}
/>
}
onCancel={onCancel}
onOK={handleOnOK}
{...rest}
/>
);
}
Example #6
Source File: helpers.ts From glide-frontend with GNU General Public License v3.0 | 6 votes |
getFormErrors = (formData: FormState, t: ContextApi['t']) => {
const { name, body, choices, startDate, startTime, endDate, endTime, snapshot } = formData
const errors: { [key: string]: string[] } = {}
if (!name) {
errors.name = [t('%field% is required', { field: 'Title' })]
}
if (!body) {
errors.body = [t('%field% is required', { field: 'Body' })]
}
if (choices.length < MINIMUM_CHOICES) {
errors.choices = [t('Please create a minimum of %num% choices', { num: MINIMUM_CHOICES })]
}
const hasEmptyChoice = choices.some((choice) => !choice.value)
if (choices.length === MINIMUM_CHOICES && hasEmptyChoice) {
errors.choices = Array.isArray(errors.choices)
? [...errors.choices, t('Choices must not be empty')]
: (errors.choices = [t('Choices must not be empty')])
}
if (!isValid(startDate)) {
errors.startDate = [t('Please select a valid date')]
}
if (!isValid(startTime)) {
errors.startTime = [t('Please select a valid time')]
}
if (!isValid(endDate)) {
errors.endDate = [t('Please select a valid date')]
}
if (!isValid(endTime)) {
errors.endTime = [t('Please select a valid time')]
}
const startDateTimestamp = combineDateAndTime(startDate, startTime)
const endDateTimestamp = combineDateAndTime(endDate, endTime)
if (endDateTimestamp < startDateTimestamp) {
errors.endDate = Array.isArray(errors.endDate)
? [...errors.endDate, t('End date must be after the start date')]
: (errors.endDate = [t('End date must be after the start date')])
}
if (snapshot === 0) {
errors.snapshot = [t('Invalid snapshot')]
}
return errors
}
Example #7
Source File: Datepicker.stories.tsx From atlas with GNU General Public License v3.0 | 6 votes |
Template: Story<DatepickerProps> = (args) => {
const ref = useRef<HTMLInputElement | null>(null)
const [date, setDate] = useState<Date | null>()
const [validationError, setValidationError] = useState(false)
const handleDateValidation = () => {
if (!date) {
return
}
setValidationError(!isValid(date))
}
return (
<>
<Datepicker {...args} ref={ref} onChange={setDate} onBlur={handleDateValidation} error={validationError} />
<span>{date ? (isValid(date) ? date.toISOString() : 'Invalid date') : 'No date'}</span>
</>
)
}
Example #8
Source File: predicates.ts From ant-extensions with MIT License | 6 votes |
isDate = (value: AnyObject): value is Date => {
try {
const parsed = parseISO(value);
return !isNaN(parsed.valueOf());
} catch {
//
}
return isValid(value);
}
Example #9
Source File: timeUtils.tsx From symphony-ui-toolkit with Apache License 2.0 | 6 votes |
getFormattedTime = (time: Time, format: string = null): string => {
if (!time) {
// Time null or undefined
return null;
}
const date = new Date();
date.setHours(
parseInt(time.hours, 10),
parseInt(time.minutes, 10),
parseInt(time.seconds, 10)
);
if (!isValid(date)) {
// Not valid
return null;
}
if (!format) {
// Return time formatted with locale time (Example: 08:50 AM or 14:55:00 ...)
return date.toLocaleTimeString();
}
// Format time
return formatTime(date, format);
}
Example #10
Source File: dateUtils.tsx From symphony-ui-toolkit with Apache License 2.0 | 6 votes |
export function autocompleteDate(value: string, format: string, locale: Locale): Date {
if (!value) {
return null;
}
const date = parse(value, format, new Date(), { locale: locale });
// If year not typed, take the current year
if (!isValid(date)) {
// regex: remove -yyyy, yyyy-, /yyyy, yyyy/, .yyyy, ...
const autocompletedDate = parse(
value,
format.replace(/[\W]?y{4}[\W]?/, ''),
new Date(),
{
locale: locale,
}
);
return autocompletedDate;
}
return date;
}
Example #11
Source File: DatePicker.tsx From symphony-ui-toolkit with Apache License 2.0 | 6 votes |
private handleInputChange(e): void {
const { format, onChange, onValidationChanged } = this.props;
const { locale } = this.state;
const newValue = e.target.value;
this.setState({ inputValue: newValue });
const newDate = autocompleteDate(newValue, format, locale);
if (newDate && isValid(newDate)) {
this.setState({ navigationDate: newDate });
}
if (onValidationChanged) {
onValidationChanged(this.computeError(newDate));
}
if (onChange) {
onChange({ target: { value: this.computeDate(newDate) } });
}
}
Example #12
Source File: AbsoluteRangePicker.tsx From gio-design with Apache License 2.0 | 5 votes |
function AbsoluteRangePicker({ disabledDate, timeRange, onSelect, onRangeSelect, onCancel }: RangePickerProps) {
const [dates, setDates] = React.useState<[Date | undefined, Date | undefined]>(parseStartAndEndDate(timeRange));
const prefixCls = usePrefixCls('range-panel__header');
const locale = useLocale('StaticPastTimePicker');
const { startDayText, endDayText, FromText, ToText } = {
...defaultLocale,
...locale,
};
const renderHeader = () => {
const placeholder = [startDayText, endDayText];
const dateString = formatDates(dates);
const dateTexts = dateString?.split('-')?.map((d) => (d === ' ' ? undefined : d)) || [];
const text = [dateTexts[0] ?? placeholder[0], dateTexts[1] ?? placeholder[1]];
return <span className={`${prefixCls}__text`}>{`${FromText} ${text[0]} ${ToText} ${text[1]}`}</span>;
};
const handleDisabledDate = (current: Date) => disabledDate?.(current) || isAfter(current, startOfToday());
const handleOnOK = () => {
onSelect(`abs:${getTime(startOfDay(dates[0] as Date))},${getTime(endOfDay(dates[1] as Date))}`);
};
const handleOnSelect = (date: [Date, Date], index: number) => {
setDates(date);
onRangeSelect?.(date, index);
}
const endDay = dates[1] !== undefined && isValid(dates[1]) ? dates[1] : new Date();
return (
<InnerRangePanel
disableOK={!isValid(dates[0]) || !isValid(dates[1])}
header={renderHeader()}
body={
<StaticDateRangePicker
defaultViewDates={[subMonths(startOfDay(endDay), 1), startOfDay(endDay)]}
disabledDate={handleDisabledDate}
onSelect={handleOnSelect}
value={dates as [Date, Date]}
/>
}
onCancel={onCancel}
onOK={handleOnOK}
/>
);
}
Example #13
Source File: DatePicker.tsx From symphony-ui-toolkit with Apache License 2.0 | 5 votes |
private computeDate(date): Date {
const { disabledDays } = this.props;
if (date && isValid(date) && !matchDay(date, disabledDays)) {
return date;
} else {
return null;
}
}
Example #14
Source File: SinceRangePicker.tsx From gio-design with Apache License 2.0 | 5 votes |
function SinceRangePicker({ disabledDate, timeRange, onSelect, onCancel, experimental, ...rest }: RangePickerProps) {
const endDateKeys = ['today', experimental ? 'yesterday' : undefined];
const dates = parseStartAndEndDate(timeRange);
const prefixCls = usePrefixCls('range-panel__header');
const [startDate, setStartDate] = React.useState<Date | undefined>(dates[0]);
const [endKey, setEndKey] = React.useState(
endDateKeys[timeRange && timeRange.split(':')[0] === 'since' ? 0 : 1] || 0
);
const locale = useLocale<typeof defaultLocale>('StaticPastTimePicker') || defaultLocale;
const { startDayText, FromText, toTodayText, toYesterdayText } = {
...defaultLocale,
...locale,
};
const END_DATE_MAPPING: Record<string, string> = {
today: toTodayText,
yesterday: toYesterdayText,
};
const renderHeader = () => {
const startDateString = startDate ? format(startDate, DATE_FORMAT) : startDayText;
return (
<>
<span className={`${prefixCls}__text`}>{`${FromText} ${startDateString}`}</span>
<span className={`${prefixCls}__options`}>
<Switch
size="small"
defaultValue={endKey}
onChange={(e) => {
setEndKey(e.target.value);
}}
>
{endDateKeys.map(
(o: string) =>
o && (
<Switch.Item key={o} value={o}>
{END_DATE_MAPPING[o]}
</Switch.Item>
)
)}
</Switch>
</span>
</>
);
};
const handleDisabledDate = (current: Date) =>
disabledDate?.(current) || isAfter(current, endKey === 'yesterday' ? startOfYesterday() : startOfToday());
const handleOnOK = () => {
onSelect(`${endKey === 'yesterday' ? 'since-lt-today' : 'since'}:${getTime(startOfDay(startDate as Date))}`);
};
return (
<InnerRangePanel
disableOK={!isValid(startDate)}
header={renderHeader()}
body={<DatePicker disabledDate={handleDisabledDate} value={startDate} onSelect={setStartDate} />}
onCancel={onCancel}
onOK={handleOnOK}
{...rest}
/>
);
}
Example #15
Source File: db.ts From command-bot with Apache License 2.0 | 5 votes |
getSortedTasks = async (
{ taskDb: { db }, logger }: Pick<Context, "taskDb" | "logger">,
{
onlyNotAlive,
}: {
onlyNotAlive?: boolean
} = {},
) => {
type Item = {
id: DbKey
queuedDate: Date
task: Task
}
const items = await new Promise<Item[]>((resolve, reject) => {
const databaseItems: Item[] = []
db.createReadStream()
.on(
"data",
({
key: rawKey,
value: rawValue,
}: {
key: ToString
value: ToString
}) => {
try {
const key = rawKey.toString()
const value = rawValue.toString()
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
const task: Task = JSON.parse(value)
if (!onlyNotAlive || !queuedTasks.has(task.id)) {
const queuedDate = parseTaskQueuedDate(task.queuedDate)
if (isValid(queuedDate)) {
databaseItems.push({ id: key, queuedDate, task })
} else {
logger.error(
{ key, value },
"Found key with invalid date in the database",
)
void db.del(key)
}
}
} catch (error) {
reject(error)
}
},
)
.on("error", (error) => {
reject(error)
})
.on("end", () => {
resolve(databaseItems)
})
})
items.sort(
(
{ queuedDate: dateA, task: taskA },
{ queuedDate: dateB, task: taskB },
) => {
if (isBefore(dateA, dateB)) {
return -1
} else if (isBefore(dateB, dateA)) {
return 1
} else if (taskA.id < taskB.id) {
return -1
} else if (taskB.id < taskA.id) {
return 1
}
return 0
},
)
return items
}
Example #16
Source File: formValidationOptions.ts From atlas with GNU General Public License v3.0 | 5 votes |
pastDateValidation = (date: Date | null, required = false) => {
if (!date) return !required
if (!isValid(date)) return false
const currentDate = new Date()
return currentDate >= date
}
Example #17
Source File: timeParser.ts From tempomat with MIT License | 5 votes |
function validDateOrNull(date: Date): Date | null {
if (isValid(date)) {
return date
} else {
return null
}
}
Example #18
Source File: Datepicker.tsx From atlas with GNU General Public License v3.0 | 5 votes |
DatepickerComponent: React.ForwardRefRenderFunction<HTMLInputElement, DatepickerProps> = (
{ name, value, required, error, disabled, helperText, onChange, onBlur },
ref
) => {
const [rawValue, setRawValue] = useState<string>()
useEffect(() => {
if (value && isValid(value)) {
setRawValue(format(value, DATE_FORMAT))
} else if (!value) {
setRawValue('')
}
}, [value])
const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => {
const value = e.target.value
setRawValue(value)
const parsedDate = value ? parse(e.target.value, DATE_FORMAT, new Date()) : null
onChange(parsedDate)
}
return (
<NumberFormat
value={rawValue}
getInputRef={ref}
customInput={TextField}
name={name}
format="##/##/####"
placeholder="DD / MM / YYYY"
mask={['D', 'D', 'M', 'M', 'Y', 'Y', 'Y', 'Y']}
helperText={helperText}
error={error}
required={required}
disabled={disabled}
onChange={handleChange}
onBlur={onBlur}
/>
)
}