core/src/common/time.ts

117 lines
2.7 KiB
TypeScript

export function toHHMMSS(input: string | number): string {
const secNum = parseInt(input.toString(), 10);
let hours: string | number = Math.floor(secNum / 3600);
let minutes: string | number = Math.floor((secNum - (hours * 3600)) / 60);
let seconds: string | number = secNum - (hours * 3600) - (minutes * 60);
if (hours < 10) {
hours = '0' + hours;
}
if (minutes < 10) {
minutes = '0' + minutes;
}
if (seconds < 10) {
seconds = '0' + seconds;
}
let time = '';
if (parseInt(hours.toString(), 10) > 0) {
time = hours + ':' + minutes + ':' + seconds;
} else {
time = minutes + ':' + seconds;
}
return time;
}
// Add a zero in front of single-digit numbers
function zf(v: number): string {
return v < 9 ? '0' + v : '' + v;
}
// Convert seconds into years days hours minutes seconds(.milliseconds)
export function readableTime(timems: number): string {
const time = Math.floor(timems);
if (time < 60) {
return zf(time) + 's';
} else if (time < 3600) {
return zf(time / 60) +
'm ' + zf(time % 60) + 's';
} else if (time < 86400) {
return zf(time / 3600) +
'h ' + zf((time % 3600) / 60) +
'm ' + zf((time % 3600) % 60) + 's';
} else if (time < 31536000) {
return (time / 86400) +
'd ' + zf((time % 86400) / 3600) +
'h ' + zf((time % 3600) / 60) +
'm ' + zf((time % 3600) % 60) + 's';
} else {
return (time / 31536000) +
'y ' + zf((time % 31536000) / 86400) +
'd ' + zf((time % 86400) / 3600) +
'h ' + zf((time % 3600) / 60) +
'm ' + zf((time % 3600) % 60) + 's';
}
}
export function parseTimeToSeconds(input: string): number {
let seconds = 0;
let match;
const secMinute = 1 * 60;
const secHour = secMinute * 60;
const secDay = secHour * 24;
const secWeek = secDay * 7;
const secYear = secDay * 365;
match = input.match('([0-9]+)y');
if (match != null) {
seconds += +match[1] * secYear;
}
match = input.match('([0-9]+)w');
if (match != null) {
seconds += +match[1] * secWeek;
}
match = input.match('([0-9]+)d');
if (match != null) {
seconds += +match[1] * secDay;
}
match = input.match('([0-9]+)h');
if (match != null) {
seconds += +match[1] * secHour;
}
match = input.match('([0-9]+)m');
if (match != null) {
seconds += +match[1] * secMinute;
}
match = input.match('([0-9]+)s');
if (match != null) {
seconds += +match[1];
}
return seconds;
}
export function thousandsSeparator(input: number | string): string {
const nStr = input.toString();
const x = nStr.split('.');
let x1 = x[0];
const x2 = x.length > 1 ? '.' + x[1] : '';
const rgx = /(\d+)(\d{3})/;
while (rgx.test(x1)) {
x1 = x1.replace(rgx, '$1' + ',' + '$2');
}
return x1 + x2;
}