Skip to content

Commit

Permalink
feat: .get
Browse files Browse the repository at this point in the history
  • Loading branch information
badosz0 committed Mar 1, 2024
1 parent 4147481 commit f9e61d7
Show file tree
Hide file tree
Showing 3 changed files with 21 additions and 8 deletions.
7 changes: 0 additions & 7 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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)
21 changes: 20 additions & 1 deletion src/time.ts
Original file line number Diff line number Diff line change
@@ -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 {
Expand Down Expand Up @@ -268,6 +268,25 @@ export class HolyTime {
return new HolyDuration(amount * HolyTime.getUnit(unit));
}

public get<T extends 'object' | GetUnit>(unit: T, timeZone?: TimeZone): T extends 'object' ? Record<GetUnit, number> : number {
const date = HolyTime.adjustToTimeZone(this.date, timeZone);

const object: Record<GetUnit, number> = {
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;
}
Expand Down
1 change: 1 addition & 0 deletions src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,4 +3,5 @@ import { HolyTime } from './time';

export type TimeResolvable = HolyTime | Date | number | string;
export type HumanUnit = `${Lowercase<keyof typeof TimeUnits>}s`;
export type GetUnit = `${Lowercase<keyof typeof TimeUnits>}`;
export type IntervalUnit = 'hour' | 'day' | 'week' | 'month' | 'year';

0 comments on commit f9e61d7

Please sign in to comment.