From f9e61d733c0dd27e28123e2352564acb89bbed7f Mon Sep 17 00:00:00 2001 From: badosz0 Date: Fri, 1 Mar 2024 18:14:56 +0100 Subject: [PATCH] feat: .get --- README.md | 7 ------- src/time.ts | 21 ++++++++++++++++++++- src/types.ts | 1 + 3 files changed, 21 insertions(+), 8 deletions(-) diff --git a/README.md b/README.md index affc4d8..2a8f79c 100644 --- a/README.md +++ b/README.md @@ -104,13 +104,6 @@ relativeFromTo(timeA: TimeResolvable, timeB: TimeResolvable): string; duration(amount: number, unit: HumanUnit): HolyDuration; ``` - -## Planned - -- [ ] .set(unit, value) -- [ ] .get(unit) -- [ ] .toObject() - ## License [MIT](https://tldrlegal.com/license/mit-license) diff --git a/src/time.ts b/src/time.ts index e53b6d9..8ab46ef 100644 --- a/src/time.ts +++ b/src/time.ts @@ -1,6 +1,6 @@ import { ValueOf } from 'type-fest'; import { DAY_NAMES, FORMAT_REGEX, MONTH_NAMES, RELATIVE_MAP, TIMEZONES, TIMEZONE_MAP, TimeUnits, TimeZone } from './constants'; -import { HumanUnit, IntervalUnit, TimeResolvable } from './types'; +import { GetUnit, HumanUnit, IntervalUnit, TimeResolvable } from './types'; import { HolyDuration } from './duration'; export class HolyTime { @@ -268,6 +268,25 @@ export class HolyTime { return new HolyDuration(amount * HolyTime.getUnit(unit)); } + public get(unit: T, timeZone?: TimeZone): T extends 'object' ? Record : number { + const date = HolyTime.adjustToTimeZone(this.date, timeZone); + + const object: Record = { + millisecond: date.getMilliseconds(), + second: date.getSeconds(), + minute: date.getMinutes(), + hour: date.getHours(), + day: date.getDate(), + week: Math.ceil(HolyTime.between(this.startOf('year', timeZone), date).in('weeks')), + month: date.getMonth() + 1, + year: date.getFullYear(), + } + + return unit === 'object' + ? object + : object[unit as GetUnit] as any + } + public getDate(): Date { return this.date; } diff --git a/src/types.ts b/src/types.ts index b739bf2..2087567 100644 --- a/src/types.ts +++ b/src/types.ts @@ -3,4 +3,5 @@ import { HolyTime } from './time'; export type TimeResolvable = HolyTime | Date | number | string; export type HumanUnit = `${Lowercase}s`; +export type GetUnit = `${Lowercase}`; export type IntervalUnit = 'hour' | 'day' | 'week' | 'month' | 'year';