expires
The expires utility determines the expiration status of a given date relative to the current time. It categorizes the date into states like EXPIRED, SOON, or LATER, making it ideal for subscription management, token validation, or deadline tracking.
Implementation
View Source Code
ts
// #region Expires
export type Expires = 'EXPIRED' | 'SOON' | 'LATER' | 'NEVER' | 'UNKNOWN';
// #endregion Expires
/**
* Determines the expiry status of a given date.
*
* @param date - The date to check, as a string or Date object.
* @param days - Number of days before expiry to be considered "SOON" (default: 7).
* @returns
* - 'EXPIRED' if the date is in the past,
* - 'SOON' if the date is within the next `days`,
* - 'LATER' if the date is further in the future,
* - 'NEVER' if the year is >= 9999,
* - 'UNKNOWN' if the date is invalid.
*/
export function expires(date: string | Date, days = 7): Expires {
const target = typeof date === 'string' ? new Date(date) : date;
const targetTime = target.getTime();
if (Number.isNaN(targetTime)) return 'UNKNOWN';
if (target.getFullYear() >= 9999) return 'NEVER';
const now = Date.now();
const diff = targetTime - now;
if (diff <= 0) return 'EXPIRED';
if (diff <= days * 24 * 60 * 60 * 1000) return 'SOON';
return 'LATER';
}Features
- Isomorphic: Works in both Browser and Node.js.
- Human-Friendly States: Returns descriptive status strings instead of raw boolean flags.
- Configurable "Soon" Window: Define exactly how many days count as "soon" for your application.
- Robust Parsing: Accepts
Dateobjects, ISO strings, or timestamps.
API
Type Definitions
ts
export type Expires = 'EXPIRED' | 'SOON' | 'LATER' | 'NEVER' | 'UNKNOWN';ts
function expires(date: string | Date, days?: number): Expires;Parameters
date: The expiration date to check.days: Optional. The number of days in the future to consider as "SOON" (defaults to7).
Returns
'EXPIRED': The date is in the past.'SOON': The date is within the specifieddayswindow.'LATER': The date is in the future, beyond the "soon" window.'NEVER': The year is 9999 or later (perpetual).'UNKNOWN': The provided date is invalid.
Examples
Basic Expiration Check
ts
import { expires } from '@vielzeug/toolkit';
// If today is 2024-01-01
expires('2023-12-31'); // 'EXPIRED'
expires('2024-01-05'); // 'SOON'
expires('2024-02-01'); // 'LATER'Custom Threshold
ts
import { expires } from '@vielzeug/toolkit';
// Consider only the next 48 hours as "SOON"
expires(someDate, 2);Implementation Notes
- Uses
Date.now()as the reference point for comparison. - Properly handles timezone differences by relying on the environment's
Dateimplementation. - Throws nothing; returns
'UNKNOWN'for malformed date inputs.