45 lines
1.4 KiB
TypeScript
45 lines
1.4 KiB
TypeScript
/**
|
|
* perform the regEx to number conversion
|
|
* @param reg
|
|
* @param timeCheck
|
|
*/
|
|
function doRegEx(reg : RegExp, timeCheck: string) : number {
|
|
|
|
if (!timeCheck || timeCheck.length === 0) return 0;
|
|
|
|
const result = reg.exec(timeCheck);
|
|
|
|
if (result && result.length > 0)
|
|
return parseInt(result[1], 10);
|
|
else return 0;
|
|
|
|
}
|
|
|
|
/**
|
|
* Get milliseconds from a string of time sections
|
|
* @param inTime *
|
|
* @signature
|
|
* U.timeToMilliseconds(inTime)
|
|
* @example
|
|
* U.timeToMilliseconds('1s') // => 1000
|
|
* U.timeToMilliseconds('1min') // => 60000
|
|
* U.timeToMilliseconds('1 weeks') // => 604800000
|
|
* U.timeToMilliseconds('5y2w30d14h30m10s') // => 161641810000
|
|
* U.timeToMilliseconds('1 hour and 5 seconds') // => 3605000
|
|
*/
|
|
|
|
export function timeToMilliseconds(inTime = '') : number {
|
|
|
|
const workTime = inTime || '';
|
|
|
|
const years = doRegEx(/(\d+)(?:\s*(?:year[s]?|y))+/gi, workTime) * 31557600000;
|
|
const weeks = doRegEx(/(\d+)(?:\s*(?:week[s]?|w))+/gi, workTime) * 604800000;
|
|
const days = doRegEx(/(\d+)(?:\s*(?:day[s]?|d))+/gi, workTime) * 86400000;
|
|
const hours = doRegEx(/(\d+)(?:\s*(?:hour[s]?|h))+/gi, workTime) * 3600000;
|
|
const minutes = doRegEx(/(\d+)(?:\s*(?:minutes[s]?|min[s]?|m))+/gi, workTime) * 60000;
|
|
const seconds = doRegEx(/(\d+)(?:\s*(?:second[s]?|sec[s]?|s))+/gi, workTime) * 1000;
|
|
|
|
return years + weeks + days + hours + minutes + seconds;
|
|
|
|
}
|