import { MaskFormatter } from "./MaskFormatter.js"; /** * `TimeFormatter`: Utilizado para formatar horas. */ export class TimeFormatter { static _maskFormatter: MaskFormatter = new MaskFormatter("##:##"); /** * Converte um texto para o formato de hora. * * @param value - Texto não formatado. * @param showSeconds - Se será validado os segundos. * @returns - Texto em formato de hora. * * @Exemples * @"1012" | "10:12" * @"10:12" | "10:12:00" * @"100112" | "10:01:12" */ static prepareValue(value: string, showSeconds: boolean): string { if (value && value.length > 0 && value != "NaN") { let validationValue = value.replace(/:/g, ""); if (showSeconds) { this._maskFormatter.mask = "##:##:##" if (validationValue.length < 6) { while (validationValue.length < 6) { validationValue = "0".concat(validationValue); } } } else { this._maskFormatter.mask = "##:##"; if (validationValue.length < 4) { while (validationValue.length < 4) { validationValue = "0".concat(validationValue); } } } if (this._maskFormatter) { try { value = this._maskFormatter.format(validationValue); return value; } catch (e:any) { throw new Error(e.message); } } } return ''; } /** * Retorna se o texto está no formato de hora. * * @param value - Texto a ser validado. * @param showSeconds - Se será validado os segundos. * @returns - Verdadeiro para valores no formato de hora e False para formatos diferentes. * * @Exemples * @"1012" | true * @"14e4" | false * @"2624" | false */ static validateTime(value: string, showSeconds: boolean) { let isValid: boolean = true; if (value) { const validationValue = value.replace(/:/g, ""); if (showSeconds) { if (!["1", "2", "0"].includes(validationValue[0])) { isValid = false; } if (!["0", "1", "2", "3", "4", "5"].includes(validationValue[2])) { isValid = false; } if (!["0", "1", "2", "3", "4", "5"].includes(validationValue[4])) { isValid = false; } if (validationValue[0] == "2" && !["0", "1", "2", "3"].includes(validationValue[1])) { isValid = false; } } else { if (!["1", "2", "0"].includes(validationValue[0])) { isValid = false; } if (!["0", "1", "2", "3", "4", "5"].includes(validationValue[2])) { isValid = false; } if (validationValue[0] == "2" && !["0", "1", "2", "3"].includes(validationValue[1])) { isValid = false; } } }else{ isValid = false; } return isValid; } }