shonen.hateblo.jp

やったこと,しらべたことを書く.

0桁埋めした文字列を返す関数

/**
 * 0埋めしたdigit桁の文字列を返す。
 * @param {number} n 非負整数
 * @param {number} digit 正整数
 */
function zeroPadding(n, digit) {
    return "0".repeat(digit).concat(n).slice(-digit);
}

他に無いらしい。時刻を指定したフォーマットで文字列に変換するメソッドが欲しかっただけなのに。

function dateToFormat(date, format = "y/m/d H:M:S") {
    let txt = "";
    for (let chr of format) {
        if (chr === 'y')
            txt = txt.concat(zeroPadding(date.getFullYear(), 4));
        else if (chr === 'm')
            txt = txt.concat(zeroPadding(date.getMonth(), 2));
        else if (chr === 'd')
            txt = txt.concat(zeroPadding(date.getDate(), 2));
        else if (chr === 'H')
            txt = txt.concat(zeroPadding(date.getHours(), 2));
        else if (chr === 'M')
            txt = txt.concat(zeroPadding(date.getMinutes(), 2));
        else if (chr === 'S')
            txt = txt.concat(zeroPadding(date.getSeconds(), 2));
        else
            txt = txt.concat(chr);
    }
    return txt;
}