Typescript: Simple date format

Date: 2022-05-30
const pad = (val: any, len: number) => String(val).padStart(len, "0");

export function formatDate (date:Date, format: string) {
    const y =  date.getFullYear(), m =  date.getMonth(), d = date.getDate();
    const h =  date.getHours(), min =  date.getMinutes(), s =  date.getSeconds();
    const f =  date.getMilliseconds();

    const arr: Array<Array<any>> = [
        ['yyyy',  y],
        ['yy', pad(y, 4).slice(2)],
        ['y', pad(y, 4).slice(3)],
        ['MM', pad(m, 2)],
        ['M', m],
        ['dd', pad(d, 2)],
        ['d', d],
        ['HH', pad(h, 2)],
        ['H', h],
        ['hh', pad(h, 2)],
        ['h', h]    ,
        ['mm', pad(min, 2)],
        ['m', min],
        ['ss', pad(s, 2)],
        ['s', s],
        ['fff', pad(f, 3)],
        ['ff', pad(f, 3).slice(0, 2)],
        ['f', pad(f, 3).slice(0, 1)]
    ];
    arr.sort((a,b) => b.length - a.length);

    let str = format;
    for (const item of arr) {
        str = str.replace(item[0], String(item[1]));
    }
    return str;
};

console.log(formatDate(new Date(1988, 10, 14, 12, 34, 55, 123), "dd-MM-yyyy HH:mm:ss.fff"));
62650cookie-checkTypescript: Simple date format