ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • JS/date format 다루기
    Language/Java Script 2021. 3. 19. 12:04

     

    date 표시할때 매번 귀찮다.

    공통으로 만들어 사용하고 있다.

     

    유틸

    /**
     * Prototype
     *
     * @author djkang
     * @since 2020. 07. 10.
     */
    
    /**
     * Date method attach
     * @param f
     * @returns {string|*}
     */
    Date.prototype.format = function (f) {
        if (!this.valueOf()) return " ";
    
        var aWeek = ['일', '월', '화', '수', '목', '금', '토'];
        var d = this;
    
        return f.replace(/(YYYY|YY|MM|DD|W|H24|HH|MINUTE|ss|a\/p)/gi, function ($1) {
            switch ($1) {
                case "YYYY":
                    return d.getFullYear();
                case "YY":
                    return (d.getFullYear() % 1000).zf(2);
                case "yy":
                    return (d.getFullYear() % 1000);
                case "MM":
                    return (d.getMonth() + 1).zf(2);
                case "mm":
                    return (d.getMonth() + 1);
                case "DD":
                    return d.getDate().zf(2);
                case "dd":
                    return d.getDate();
                case "W":
                    return aWeek[d.getDay()];
                case "H24":
                    return d.getHours().zf(2);
                case "h24":
                    return d.getHours();
                case "HH":
                    return ((h = d.getHours() % 12) ? h : 12).zf(2);
                case "hh":
                    return ((h = d.getHours() % 12) ? h : 12);
                case "MINUTE":
                    return d.getMinutes().zf(2);
                case "minute":
                    return d.getMinutes();
                case "SS":
                    return d.getSeconds().zf(2);
                case "ss":
                    return d.getSeconds();
                case "a/p":
                    return d.getHours() < 12 ? "오전" : "오후";
                default:
                    return $1;
            }
        });
    };
    String.prototype.string = function (len) {
        var s = '', i = 0;
        while (i++ < len) {
            s += this;
        }
        return s;
    };
    String.prototype.zf = function (len) {
        return "0".string(len - this.length) + this;
    };
    Number.prototype.zf = function (len) {
        return this.toString().zf(len);
    };

     

     

    사용방법

    console.log(new Date('2020-03-12 14:30:20').format('H24:MINUTE'));
    console.log(new Date().format('YYYY. MM. DD H24:MINUTE'));

    댓글

Designed by Tistory.