Options
All
  • Public
  • Public/Protected
  • All
Menu

@thi.ng/date

Index

Type aliases

EpochIterator

EpochIterator: IterableIterator<number>

FormatFn

FormatFn: Fn2<Date, boolean, string>

LocaleSpec

LocaleSpec: Pick<Locale, "months" | "days"> & Partial<Omit<Locale, "months" | "days">>

A partially optional version of Locale, for use with setLocale.

MaybeDate

MaybeDate: DateTime | Date | number | string

Period

Period: Precision | "w" | "q"

Precision

Precision: "y" | "M" | "d" | "h" | "m" | "s" | "t"

DateTime precision/resolution IDs:

  • y : year
  • M : month
  • d : day
  • h : hour
  • m : minute
  • s : second
  • t : millisecond

RoundingFn

RoundingFn: Fn<MaybeDate, number>

Date rounding function for MaybeDate inputs.

Variables

DAY

DAY: number = ...

Day duration in milliseconds

DAYS_IN_400YEARS

DAYS_IN_400YEARS: number = ...

There're 97 leap years and 303 normal years per 400 years

DAYS_IN_MONTH

DAYS_IN_MONTH: number[] = ...

Days per month LUT (non-leap year)

DAYS_IN_MONTH_OFFSET

DAYS_IN_MONTH_OFFSET: number[] = ...

LUT of day-in-year values for 1st of each month (non-leap year)

DE_LONG

DE_LONG: LocaleSpec = ...

DE_SHORT

DE_SHORT: LocaleSpec = ...

EN_LONG

EN_LONG: LocaleSpec = ...

EN_SHORT

EN_SHORT: LocaleSpec = ...

ES_LONG

ES_LONG: LocaleSpec = ...

FORMATTERS

FORMATTERS: Record<string, FormatFn> = ...

FR_LONG

FR_LONG: LocaleSpec = ...

HOUR

HOUR: number = ...

Hour duration in milliseconds

IT_LONG

IT_LONG: LocaleSpec = ...

LOCALE

LOCALE: Locale = ...

MINUTE

MINUTE: number = ...

Minute duration in milliseconds

MONTH

MONTH: number = ...

Mean month duration (30.436875 days) in milliseconds

SECOND

SECOND: 1000 = 1000

Second duration in milliseconds

WEEK

WEEK: number = ...

Week duration in milliseconds

YEAR

YEAR: number = ...

Mean year duration (365.2425 days) in milliseconds

Functions

Const FMT_HHmm

  • FMT_HHmm(x: MaybeDate, utc?: boolean): string

Const FMT_HHmmss

  • FMT_HHmmss(x: MaybeDate, utc?: boolean): string

Const FMT_ISO

  • ISO8601 format preset (with millisecond term), e.g. 2020-09-19T17:08:01.123Z

    Parameters

    Returns string

Const FMT_ISO_SHORT

  • FMT_ISO_SHORT(x: MaybeDate, utc?: boolean): string
  • ISO8601 format preset (without millisecond term), e.g. 2020-09-19T17:08:01Z

    Parameters

    Returns string

Const FMT_MMMdyyyy

  • FMT_MMMdyyyy(x: MaybeDate, utc?: boolean): string

Const FMT_Mdyyyy

  • FMT_Mdyyyy(x: MaybeDate, utc?: boolean): string

Const FMT_dMMMyyyy

  • FMT_dMMMyyyy(x: MaybeDate, utc?: boolean): string
  • Format preset, e.g. 19 Sep 2020

    Parameters

    Returns string

Const FMT_dMyyyy

  • FMT_dMyyyy(x: MaybeDate, utc?: boolean): string

Const FMT_hm

Const FMT_hms

  • Format preset, e.g. 5:08:01 PM

    Parameters

    Returns string

Const FMT_yyyyMMdd

  • FMT_yyyyMMdd(x: MaybeDate, utc?: boolean): string
  • Format preset, e.g. 2020-09-19

    Parameters

    Returns string

Const FMT_yyyyMMdd_HHmmss

  • FMT_yyyyMMdd_HHmmss(x: MaybeDate, utc?: boolean): string
  • Format preset, e.g. 20200919-170801

    Parameters

    Returns string

Const ceilDay

Const ceilHour

Const ceilMinute

Const ceilMonth

Const ceilQuarter

  • Rounds up epoch to month precision (beginning of next quarter)

    Parameters

    Returns number

Const ceilSecond

Const ceilWeek

  • Rounds up epoch to week precision. Assumes ISO8601 week logic, i.e. weeks start on Monday.

    Parameters

    Returns number

Const ceilYear

Const dateTime

Const dayInYear

  • dayInYear(a: number, b: number, c: number): number
  • Parameters

    • a: number
    • b: number
    • c: number

    Returns number

Const days

  • Yields iterator of UTC timestamps in given semi-open interval in daily precision (each timestamp is at midnight/beginning of each day).

    Parameters

    Returns EpochIterator

  • Yields iterator of UTC timestamps in given semi-open interval in daily precision (each timestamp is at midnight/beginning of each day).

    Parameters

    Returns EpochIterator

Const daysInMonth

  • daysInMonth(a: number, b: number): number
  • Parameters

    • a: number
    • b: number

    Returns number

Const decomposeDifference

  • Computes and decomposes difference between given dates. Returns tuple of: [sign, years, months, days, hours, mins, secs, millis]. The sign is used to indicate the relative order of a compared to b, i.e. same contract as ICompare.

    Parameters

    Returns number[]

Const decomposeDuration

  • decomposeDuration(dur: number): number[]
  • Decomposes given duration (in milliseconds) into a tuple of: [year, month, day, hour, minute, second, millis].

    Parameters

    • dur: number

    Returns number[]

Const defFormat

  • Returns a new date formatter for given array of format strings (or functions). The returned function accepts timestamps (epoch), Date or DateTime instances and accepts an optional boolean arg to output UTC instead of local time (default).

    remarks

    See FORMATTERS for available date component format IDs. To escape a formatter and use as a string literal, prefix the term with \\.

    example
    const fmt = defFormat(["yyyy", "-", "MM", "-", "dd"]);

    fmt(new Date(2015, 3, 23))
    // "2015-04-23"

    defFormat(["\\yyyy"])(new Date(2015, 3, 23))
    // "yyyy"

    Parameters

    Returns (x: MaybeDate, utc?: boolean) => string

      • Parameters

        Returns string

Const defIterator

Const defTimecode

  • defTimecode(fps: number, sep?: ArrayLike<string>): (t: number) => string
  • Returns a time formatter for given FPS (frames / second, in [1..1000] range), e.g. HH:mm:ss:ff. The returned function takes a single arg (time in milliseconds) and returns formatted string.

    remarks

    The timecode considers days too, but only includes them in the result if the day part is non-zero. The 4 separators between each field can be customized via 2nd arg (default: all :).

    example
    a = defTimecode(30);
    a(HOUR + 2*MINUTE + 3*SECOND + 4*1000/30)
    // "01:02:03:04"

    a(DAY);
    // "01:00:00:00:00"

    b = defTimecode(30, ["d ", "h ", "' ", '" ']);
    b(Day + HOUR + 2*MINUTE + 3*SECOND + 999)
    // "01d 01h 02' 03" 29"

    Parameters

    • fps: number
    • sep: ArrayLike<string> = "::::"

    Returns (t: number) => string

      • (t: number): string
      • Parameters

        • t: number

        Returns string

Const difference

Const ensureDate

Const ensureDateTime

Const ensureEpoch

Const floorDay

Const floorHour

Const floorMinute

Const floorMonth

Const floorQuarter

  • Rounds down epoch to month precision, but at beginning of a quarter.

    Parameters

    Returns number

Const floorSecond

  • Rounds down epoch to minute precision.

    Parameters

    Returns number

Const floorWeek

  • Rounds down epoch to week precision. Assumes ISO8601 week logic, i.e. weeks start on Monday.

    Parameters

    Returns number

Const floorYear

Const formatRelative

  • Takes a date and optional reference base date and (also optional precision, i.e. number of fractional digits, default: 0). Computes the difference between given dates and returns it as formatted string.

    remarks

    Returns {@link LOCALE.now} if absolute difference is < eps milliseconds (default: 100).

    see

    formatRelativeParts for alternative output.

    example
    formatRelative("2020-06-01", "2021-07-01")
    // "1 year ago"

    formatRelative("2020-08-01", "2021-07-01")
    // "11 months ago"

    formatRelative("2021-07-01 13:45", "2021-07-01 12:05")
    // "in 2 hours"

    formatRelative("2021-07-01 12:23:24", "2021-07-01 12:05")
    // "in 18 minutes"

    Parameters

    Returns string

Const formatRelativeParts

  • Similar to formatRelative, however precision is specified as Precision (default: seconds). The result will be formatted as a string made up of parts of increasing precision (years, months, days, hours, etc.). Only non-zero parts will be mentioned.

    remarks

    Returns {@link LOCALE.now} if absolute difference is < eps milliseconds (default: 100). In all other cases uses decomposeDifference for given dates to extract parts for formatting.

    example
    // with default precision (seconds)
    formatRelativeParts("2022-09-01 12:23:24", "2021-07-01 12:05")
    // "in 1 year, 2 months, 21 hours, 18 minutes, 24 seconds"

    // with day precision
    formatRelativeParts("2012-12-25 17:59", "2021-07-01 12:05", "d")
    // "8 years, 6 months, 5 days ago"

    formatRelativeParts("2021-07-01 17:59", "2021-07-01 12:05", "d")
    // "in less than a day"

    Parameters

    Returns string

Const hours

Const isLeapYear

  • isLeapYear(year: number): boolean
  • Parameters

    • year: number

    Returns boolean

Const maybeIsDate

  • maybeIsDate(x: any): boolean

Const milliseconds

Const minutes

Const monthNames

  • monthNames(): string[]
  • Returns a copy of current LOCALE's month names array.

    Returns string[]

Const months

  • Yields iterator of UTC timestamps in given semi-open interval in monthly precision (each timestamp is at beginning of each month).

    Parameters

    Returns EpochIterator

  • Yields iterator of UTC timestamps in given semi-open interval in monthly precision (each timestamp is at beginning of each month).

    Parameters

    Returns EpochIterator

Const parseRelative

  • Takes a relative time offset string in plain english and an optional base date (default: now). Parses offset and returns new date with relative offset applied. Returns undefined if parsing failed.

    remarks

    This function only handles the parsing and input normalization aspect for relative. The latter function applies the actual offset.

    The following input formats are supported:

    • "tomorrow" / "yesterday" - ±1 day
    • any weekday names in EN_SHORT and EN_LONG (always in future)
    • <"-"|"+">?<num><period><" ago">?" - ±num periods (if prefixed with "-" or if the " ago" suffix is given, the offset will be applied towards the past)

    (Note: If both negative offset and "ago" is given, the suffix will, like a double-negative, flip the direction back towards the future).

    If using the latter form:

    • <num> can be a positve integer or strings: "next ", "a " or "an "
    • <period> can be:
      • ms / millis / millisecond / milliseconds
      • s / sec / secs / second / seconds
      • min / mins / minute / minutes
      • h / hour / hours
      • d / day / days
      • w / week / weeks
      • month / months
      • q / quarter / quarters
      • y / year / years

    Parameters

    Returns undefined | DateTime

Const quarters

  • Yields iterator of UTC timestamps in given semi-open interval in monthly precision (each timestamp is at beginning of a month), but spaced at 3 month intervals.

    Parameters

    Returns EpochIterator

  • Yields iterator of UTC timestamps in given semi-open interval in monthly precision (each timestamp is at beginning of a month), but spaced at 3 month intervals.

    Parameters

    Returns EpochIterator

Const relative

  • Applies the given relative offset (defined by num and period) to the optionally given base date (default: now). If num < 0 the result date will be in the past (relative to base).

    Parameters

    Returns DateTime

Const seconds

Const setLocale

Const tense

  • tense(sign: number, res: string): string
  • Wraps given (presumably localized) string in current LOCALE's past or future phrases, depending on given sign.

    Parameters

    • sign: number
    • res: string

    Returns string

Const units

  • Returns a suitable version of requested unit from current LOCALE, based on quantity x and optional dativ grammar form. If unitsOnly is true (default false) only the unit (w/o quantity) will be returned.

    remarks

    Also see unitsLessThan, formatRelative, formatRelativeParts.

    example
    withLocale(FR_LONG, () => units(1, "y"));
    // "1 année"

    withLocale(FR_LONG, () => units(1, "y", true));
    // "1 an"

    withLocale(FR_LONG, () => units(2, "y"));
    // "2 ans"

    withLocale(FR_LONG, () => units(2, "y", true));
    // "2 ans"

    withLocale(DE_LONG, () => units(2, "y"));
    // "2 Jahre"

    withLocale(DE_LONG, () => units(2, "y", true));
    // "2 Jahren"

    Parameters

    Returns string

Const unitsLessThan

  • Similar to units, but for cases to express/format the phrase less than {x} {unit(s)}.

    example
    withLocale(DE_LONG, () => unitsLessThan(1, "y"));
    // "weniger als 1 Jahr"

    Parameters

    Returns string

Const weekInYear

  • weekInYear(a: number, b: number, c: number): number
  • Parameters

    • a: number
    • b: number
    • c: number

    Returns number

Const weekdayNames

  • weekdayNames(): string[]
  • Returns a copy of current LOCALE's weekday names array.

    Returns string[]

Const weeks

  • Yields iterator of UTC timestamps in given semi-open interval in daily precision (each timestamp is 7 days apart). As per ISO8601, weeks start on Mondays.

    Parameters

    Returns EpochIterator

  • Yields iterator of UTC timestamps in given semi-open interval in daily precision (each timestamp is 7 days apart). As per ISO8601, weeks start on Mondays.

    Parameters

    Returns EpochIterator

Const withLocale

  • Executes given fn with temporarily active locale. Returns result of fn.

    remarks

    fn will be called within a try/catch block and the previous locale will be restored even if fn throws an error.

    Type parameters

    • T

    Parameters

    Returns T

Const years

  • Yields iterator of UTC timestamps in given semi-open interval in yearly precision (each timestamp is at beginning of each year).

    Parameters

    Returns EpochIterator

  • Yields iterator of UTC timestamps in given semi-open interval in yearly precision (each timestamp is at beginning of each year).

    Parameters

    Returns EpochIterator

Generated using TypeDoc