import { format as fnsFormat, parse as fnsParse } from 'date-fns'; export function toBoolean(value: boolean | string): boolean { return !!value; } export function convertToDate(value: string, format: string = 'hh:mm:ss'): Date { if (!value || !format) { return; } // let hours = '0'; // let minutes = '0'; // let seconds = '0'; // const formatSArr = format.split(' ')[0]; // const formatEArr = format.split(' ')[1]; // const formatArr = formatSArr.split(':'); // const textArr = value.split(' ')[0].split(':'); // // tslint:disable-next-line:variable-name // const AMOrPM = value.split(' ')[1]; // formatArr.forEach((item: string, index: number) => { // item = item.toUpperCase(); // if (item === 'H' || item === 'HH') { // hours = textArr[index]; // } else if (item === 'M' || item === 'MM') { // minutes = textArr[index]; // } else if (item === 'S' || item === 'SS') { // seconds = textArr[index]; // } else if (item === 'A') { // } // }); // if (formatEArr && formatEArr.toUpperCase() === 'A') { // if (AMOrPM === 'PM') { // hours = Number(hours) + 12 + ''; // } // } // return new Date( // 1970, // 0, // 1, // Number(hours), // Number(minutes), // Number(seconds) // ); if (format.indexOf('ss') === -1 && value.split(':').length === 3) { format = format + ':ss'; } return fnsParse(value, format, new Date()); } export function convertToStr( date: Date, format: string = 'hh:mm:ss', selected12Hours = 'AM' ) { if (!date || isNaN(date.getTime())) { return ''; } // let _hours = date.getHours(); // selected12Hours = selected12Hours ? selected12Hours : 'AM'; // if (selected12Hours === 'PM') { // _hours = _hours > 12 ? _hours - 12 : _hours; // } // const hours = addZero(_hours); // const minutes = addZero(date.getMinutes()); // const seconds = addZero(date.getSeconds()); // if (format.indexOf('a') >= 0 || format.indexOf('A') >= 0) { // format = format.replace(/a/i, selected12Hours); // } // if (format.indexOf('hh') >= 0 || format.indexOf('HH') >= 0) { // format = format.replace(/hh/i, hours); // } else if (format.indexOf('h') >= 0 || format.indexOf('H') >= 0) { // format = format.replace(/h/i, hours); // } // if (format.indexOf('mm') >= 0 || format.indexOf('MM') >= 0) { // format = format.replace(/mm/i, minutes); // } else if (format.indexOf('m') >= 0 || format.indexOf('M') >= 0) { // format = format.replace(/m/i, minutes); // } // if (format.indexOf('ss') >= 0 || format.indexOf('SS') >= 0) { // format = format.replace(/ss/i, seconds); // } else if (format.indexOf('s') >= 0 || format.indexOf('S') >= 0) { // format = format.replace(/s/i, seconds); // } // return format; return fnsFormat(date, format); } export function addZero(val: any) { val = String(val); if (val.length === 1) { return '0' + val; } return val; }