UNPKG

@naturalcycles/js-lib

Version:

Standard library for universal (browser + Node.js) javascript

331 lines (330 loc) 12.6 kB
import type { IANATimezone, Inclusiveness, IsoDate, IsoDateTime, IsoMonth, MutateOptions, NumberOfHours, NumberOfMinutes, SortDirection, UnixTimestamp, UnixTimestampMillis } from '../types.js'; import type { LocalDate } from './localDate.js'; import { WallTime } from './wallTime.js'; export type LocalTimeUnit = 'year' | 'month' | 'week' | 'day' | 'hour' | 'minute' | 'second'; export declare enum ISODayOfWeek { MONDAY = 1, TUESDAY = 2, WEDNESDAY = 3, THURSDAY = 4, FRIDAY = 5, SATURDAY = 6, SUNDAY = 7 } export type LocalTimeInput = LocalTime | Date | IsoDate | IsoDateTime | UnixTimestamp; export type LocalTimeInputNullable = LocalTimeInput | null | undefined; export type LocalTimeFormatter = (ld: LocalTime) => string; export type DateTimeObject = DateObject & TimeObject; export type DateTimeObjectInput = DateObject & Partial<TimeObject>; export interface DateObject { year: number; month: number; day: number; } export interface TimeObject { hour: number; minute: number; second: number; } export declare const VALID_DAYS_OF_WEEK: Set<number>; export declare class LocalTime { $date: Date; constructor($date: Date); /** * Returns [cloned] LocalTime that is based on the same unixtimestamp, but in UTC timezone. * Opposite of `.local()` method. */ toUTC(): LocalTime; /** * Returns [cloned] LocalTime that is based on the same unixtimestamp, but in local timezone. * Opposite of `.utc()` method. */ toLocal(): LocalTime; /** * Returns [cloned] fake LocalTime that has yyyy-mm-dd hh:mm:ss in the provided timezone. * It is a fake LocalTime in a sense that it's timezone is not real. * See this ("common errors"): https://stackoverflow.com/a/15171030/4919972 * Fake also means that unixTimestamp of that new LocalDate is not the same. * For that reason we return WallTime, and not a LocalTime. * WallTime can be pretty-printed as Date-only, Time-only or DateAndTime. * * E.g `inTimezone('America/New_York').toISOTime()` * * https://en.wikipedia.org/wiki/List_of_tz_database_time_zones * * @experimental */ inTimezone(tz: IANATimezone): WallTime; /** * UTC offset is the opposite of "timezone offset" - it's the number of minutes to add * to the local time to get UTC time. * * E.g utcOffset for CEST is -120, * which means that you need to add -120 minutes to the local time to get UTC time. * * Instead of -0 it returns 0, for the peace of mind and less weird test/snapshot differences. * * If timezone (tz) is specified, e.g `America/New_York`, * it will return the UTC offset for that timezone. * * https://en.wikipedia.org/wiki/List_of_tz_database_time_zones */ getUTCOffsetMinutes(tz?: IANATimezone): NumberOfMinutes; /** * Same as getUTCOffsetMinutes, but rounded to hours. * * E.g for CEST it is -2. * * Instead of -0 it returns 0, for the peace of mind and less weird test/snapshot differences. * * If timezone (tz) is specified, e.g `America/New_York`, * it will return the UTC offset for that timezone. */ getUTCOffsetHours(tz?: IANATimezone): NumberOfHours; /** * Returns e.g `-05:00` for New_York winter time. */ getUTCOffsetString(tz: IANATimezone): string; get(unit: LocalTimeUnit): number; set(unit: LocalTimeUnit, v: number, opt?: MutateOptions): LocalTime; get year(): number; setYear(v: number): LocalTime; get month(): number; setMonth(v: number): LocalTime; get week(): number; setWeek(v: number): LocalTime; get day(): number; setDay(v: number): LocalTime; get hour(): number; setHour(v: number): LocalTime; get minute(): number; setMinute(v: number): LocalTime; get second(): number; setSecond(v: number): LocalTime; /** * Based on ISO: 1-7 is Mon-Sun. */ get dayOfWeek(): ISODayOfWeek; /** * Returns LocalTime for the given DayOfWeek (e.g Monday), that is in the same week as this. * It may move the time into the future, or the past, depending on how the desired DayOfWeek is in * relation to `this`. */ setDayOfWeek(dow: ISODayOfWeek): LocalTime; /** * Returns LocalTime for the given DayOfWeek (e.g Monday), that is in the future, * in relation to this. * If this LocalTime is Monday, and desired DoW is also Monday - `this` is returned. */ setNextDayOfWeek(dow: ISODayOfWeek): LocalTime; setComponents(c: Partial<DateTimeObject>, opt?: MutateOptions): LocalTime; plusSeconds(num: number): LocalTime; plusMinutes(num: number): LocalTime; plusHours(num: number): LocalTime; plusDays(num: number): LocalTime; plusWeeks(num: number): LocalTime; plusMonths(num: number): LocalTime; plusYears(num: number): LocalTime; minusSeconds(num: number): LocalTime; minusMinutes(num: number): LocalTime; minusHours(num: number): LocalTime; minusDays(num: number): LocalTime; minusWeeks(num: number): LocalTime; minusMonths(num: number): LocalTime; minusYears(num: number): LocalTime; plus(num: number, unit: LocalTimeUnit, opt?: MutateOptions): LocalTime; minus(num: number, unit: LocalTimeUnit, opt?: MutateOptions): LocalTime; absDiff(other: LocalTimeInput, unit: LocalTimeUnit): number; diff(other: LocalTimeInput, unit: LocalTimeUnit): number; startOf(unit: LocalTimeUnit, opt?: MutateOptions): LocalTime; endOf(unit: LocalTimeUnit, opt?: MutateOptions): LocalTime; /** * Returns how many days are in the current month. * E.g 31 for January. */ get daysInMonth(): number; isSame(d: LocalTimeInput): boolean; isBefore(d: LocalTimeInput, inclusive?: boolean): boolean; isSameOrBefore(d: LocalTimeInput): boolean; isAfter(d: LocalTimeInput, inclusive?: boolean): boolean; isSameOrAfter(d: LocalTimeInput): boolean; isBetween(min: LocalTimeInput, max: LocalTimeInput, incl: Inclusiveness): boolean; /** * Checks if this localTime is older (<) than "now" by X units. * * Example: * * localTime(expirationDate).isOlderThan(5, 'day') * * Third argument allows to override "now". */ isOlderThan(n: number, unit: LocalTimeUnit, now?: LocalTimeInput): boolean; /** * Checks if this localTime is same or older (<=) than "now" by X units. */ isSameOrOlderThan(n: number, unit: LocalTimeUnit, now?: LocalTimeInput): boolean; /** * Checks if this localTime is younger (>) than "now" by X units. * * Example: * * localTime(expirationDate).isYoungerThan(5, 'day') * * Third argument allows to override "now". */ isYoungerThan(n: number, unit: LocalTimeUnit, now?: LocalTimeInput): boolean; /** * Checks if this localTime is same or younger (>=) than "now" by X units. */ isSameOrYoungerThan(n: number, unit: LocalTimeUnit, now?: LocalTimeInput): boolean; getAgeInYears(now?: LocalTimeInput): number; getAgeInMonths(now?: LocalTimeInput): number; getAgeInDays(now?: LocalTimeInput): number; getAgeInHours(now?: LocalTimeInput): number; getAgeInMinutes(now?: LocalTimeInput): number; getAgeInSeconds(now?: LocalTimeInput): number; getAgeIn(unit: LocalTimeUnit, now?: LocalTimeInput): number; isAfterNow(): boolean; isBeforeNow(): boolean; /** * Returns 1 if this > d * returns 0 if they are equal * returns -1 if this < d */ compare(d: LocalTimeInput): -1 | 0 | 1; toDateTimeObject(): DateTimeObject; toDateObject(): DateObject; toTimeObject(): TimeObject; toFromNowString(now?: LocalTimeInput): string; toDate(): Date; clone(): LocalTime; get unix(): UnixTimestamp; get unixMillis(): UnixTimestampMillis; valueOf(): UnixTimestamp; toLocalDate(): LocalDate; /** * Returns e.g: `1984-06-21 17:56:21` * or (if seconds=false): * `1984-06-21 17:56` */ toPretty(seconds?: boolean): IsoDateTime; /** * Returns e.g: `1984-06-21T17:56:21` */ toISODateTime(): IsoDateTime; /** * Returns e.g: `1984-06-21`, only the date part of DateTime */ toISODate(): IsoDate; /** * Returns e.g: `1984-06` */ toISOMonth(): IsoMonth; /** * Returns e.g: `17:03:15` (or `17:03` with seconds=false) */ toISOTime(seconds?: boolean): string; toWallTime(): WallTime; /** * Returns e.g: `19840621_1705` */ toStringCompact(seconds?: boolean): string; toString(): IsoDateTime; toJSON(): UnixTimestamp; format(fmt: Intl.DateTimeFormat | LocalTimeFormatter): string; } declare class LocalTimeFactory { /** * Creates a LocalTime from the input, unless it's falsy - then returns undefined. * * `localTime` function will instead return LocalTime of `now` for falsy input. */ orUndefined(input: LocalTimeInputNullable): LocalTime | undefined; /** * Creates a LocalTime from the input, unless it's falsy - then returns LocalTime.now */ orNow(input: LocalTimeInputNullable): LocalTime; now(): LocalTime; /** Convenience function to return current Unix timestamp in seconds. Like Date.now(), but in seconds. */ nowUnix(): UnixTimestamp; /** Convenience function that retuns the same as Date.now(), but with proper type of UnixTimestampMillis. */ nowUnixMillis(): UnixTimestampMillis; /** * Create LocalTime from LocalTimeInput. * Input can already be a LocalTime - it is returned as-is in that case. * Date - will be used as-is. * String - will be parsed as strict `yyyy-mm-ddThh:mm:ss`. * Number - will be treated as unix timestamp in seconds. */ fromInput(input: LocalTimeInput): LocalTime; /** * Returns true if input is valid to create LocalTime. */ isValid(input: LocalTimeInputNullable): boolean; /** * Returns true if isoString is a valid iso8601 string like `yyyy-mm-ddThh:mm:dd`. */ isValidString(isoString: IsoDateTime | IsoDate | undefined | null): boolean; /** * Tries to convert/parse the input into LocalTime. * Uses LOOSE parsing. * If invalid - doesn't throw, but returns undefined instead. */ try(input: LocalTimeInputNullable): LocalTime | undefined; /** * Performs STRICT parsing. * Only allows IsoDateTime or IsoDate input, nothing else. */ fromIsoDateTimeString(s: IsoDateTime | IsoDate): LocalTime; /** * Performs LOOSE parsing. * Tries to coerce imprefect/incorrect string input into IsoDateTimeString. * Use with caution. * Allows to input IsoDate, will set h:m:s to zeros. */ parse(s: string): LocalTime; private parseStrictlyOrUndefined; private parseLooselyOrUndefined; /** * Throws on invalid value. */ validateDateTimeObject(o: DateTimeObject): void; isDateTimeObjectValid(o: DateTimeObject): boolean; isTimeObjectValid({ hour, minute, second }: TimeObject): boolean; fromDate(date: Date): LocalTime; fromUnix(ts: UnixTimestamp): LocalTime; /** * Create LocalTime from unixTimestamp in milliseconds (not in seconds). */ fromMillis(millis: UnixTimestampMillis): LocalTime; fromDateTimeObject(o: DateTimeObjectInput): LocalTime; private createDateFromDateTimeObject; /** * Returns the IANA timezone e.g `Europe/Stockholm`. * https://en.wikipedia.org/wiki/List_of_tz_database_time_zones */ getTimezone(): IANATimezone; /** * Returns true if passed IANA timezone is valid/supported. * E.g `Europe/Stockholm` is valid, but `Europe/Stockholm2` is not. * * This implementation is not optimized for performance. If you need frequent validation - * consider caching the Intl.supportedValuesOf values as Set and reuse that. */ isTimezoneValid(tz: string): boolean; sort(items: LocalTime[], dir?: SortDirection, opt?: MutateOptions): LocalTime[]; minOrUndefined(items: LocalTimeInputNullable[]): LocalTime | undefined; min(items: LocalTimeInputNullable[]): LocalTime; maxOrUndefined(items: LocalTimeInputNullable[]): LocalTime | undefined; max(items: LocalTimeInputNullable[]): LocalTime; } interface LocalTimeFn extends LocalTimeFactory { (d: LocalTimeInput): LocalTime; } export declare const localTime: LocalTimeFn; export {};