add duration utils docs (#35995)

This commit is contained in:
Domas 2021-06-21 18:41:11 +03:00 committed by GitHub
parent 781ab833bd
commit bef0f797ab
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

View File

@ -32,6 +32,13 @@ export function intervalToAbbreviatedDurationString(interval: Interval, includeS
}, ''); }, '');
} }
/**
* parseDuration parses duration string into datefns Duration object
*
* @param duration - string to convert. For example '2m', '5h 20s'
*
* @public
*/
export function parseDuration(duration: string): Duration { export function parseDuration(duration: string): Duration {
return duration.split(' ').reduce<Duration>((acc, value) => { return duration.split(' ').reduce<Duration>((acc, value) => {
const match = value.match(/(\d+)(.+)/); const match = value.match(/(\d+)(.+)/);
@ -44,15 +51,37 @@ export function parseDuration(duration: string): Duration {
}, {}); }, {});
} }
/**
* addDurationToDate adds given duration to given date and returns a new Date object
*
* @param date - date to add to. Can be either Date object or a number (milliseconds since epoch)
* @param duration - duration to add. For example '2m', '5h 20s'
*
* @public
*/
export function addDurationToDate(date: Date | number, duration: Duration): Date { export function addDurationToDate(date: Date | number, duration: Duration): Date {
return add(date, duration); return add(date, duration);
} }
/**
* durationToMilliseconds convert a duration object to milliseconds
*
* @param duration - datefns Duration object
*
* @public
*/
export function durationToMilliseconds(duration: Duration): number { export function durationToMilliseconds(duration: Duration): number {
const now = new Date(); const now = new Date();
return addDurationToDate(now, duration).getTime() - now.getTime(); return addDurationToDate(now, duration).getTime() - now.getTime();
} }
export function isValidDate(dateString: string) { /**
* isValidDate returns true if given string can be parsed into valid Date object, false otherwise
*
* @param dateString - string representation of a date
*
* @public
*/
export function isValidDate(dateString: string): boolean {
return !isNaN(Date.parse(dateString)); return !isNaN(Date.parse(dateString));
} }