Skip to content

Clearer representation of dates in ISO (and ISO-like) strings

Choose a tag to compare

@uatisdeproblem uatisdeproblem released this 19 Apr 13:20
· 26 commits to main since this release

We had to fix the previous naming structure for ISO dates (and date strings) to ensure the name reflected the actual behaviour of the expected strings (epoch vs NOT epoch dates). The earlier names for affected types and functions are still available but are considered deprecated.

Types

/**
 * It's a date time stored as ISO string `YYYY-MM-DDTHH:mm:ss.sssZ`.
 * The timezone is always UTC, as denoted by the suffix `Z`.
 * The type is an alias to avoid further explanation for each variable.
 */
export type ISOString = string; // previously "epochISOString"
/*
 * It's a date time stored as ISO string: `YYYY-MM-DD`.
 * It doesn't say anything about the timezone.
 * The type is an alias to avoid further explanation for each variable.
 */
export type ISODateString = string; // previously "epochISODateString"

Functions

/**
 * Get the ISO string version of a date in the format `YYYY-MM-DDTHH:mm:ss.sssZ`.
 * The timezone is always UTC, as denoted by the suffix `Z`.
 */
export const toISOString = (input: Date | number | ISOString | ISODateString): ISOString | null => {
  if (!input) return null;
  const date = input instanceof Date ? input : new Date(input);
  return date.toISOString();
};
/**
 * Get the current date and time in the format `YYYY-MM-DDTHH:mm:ss.sssZ`.
 * The timezone is always UTC, as denoted by the suffix `Z`.
 */
export const nowISOString = (): ISOString => toISOString(new Date());

/**
 * Get the ISO string version of a date in the format `YYYY-MM-DD`.
 * It doesn't say anything about the timezone.
 */
export const toISODateString = (input: Date | number | ISOString | ISODateString): ISODateString | null => {
  if (!input) return null;
  /// it forces the internal time to 12.00 to make the date timezone-resistant
  const dateResistantToTimeZones = new Date(input);
  dateResistantToTimeZones.setHours(12, 0, 0, 0);
  return dateResistantToTimeZones.toISOString().slice(0, 10);
};
/**
 * @deprecated use toISODateString instead
 */
export const toISODate = toISODateString;
/**
 * Get the current date in the format `YYYY-MM-DD`.
 * It doesn't say anything about the timezone.
 */
export const nowISODateString = (): ISODateString => toISODateString(new Date());