Notice
Recent Posts
Recent Comments
Link
«   2025/07   »
1 2 3 4 5
6 7 8 9 10 11 12
13 14 15 16 17 18 19
20 21 22 23 24 25 26
27 28 29 30 31
Archives
Today
Total
관리 메뉴

유령노트

JS DATE에 FORMAT 프로토타입 추가 본문

# Dev/Javascript

JS DATE에 FORMAT 프로토타입 추가

유령손 2021. 8. 13. 14:18
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
//date prototype 추가
Date.prototype.format = function(f) {
    if (!this.valueOf()) return " ";
 
    var weekName = ["일""월""화""수""목""금""토"];
    var d = this;
     
    return f.replace(/(yyyy|yy|MM|dd|E|hh|mm|ss|ms|a\/p)/gi, function($1) {
        switch ($1) {
            case "yyyy"return d.getFullYear();
            case "yy"return (d.getFullYear() % 1000).zf(2);
            case "MM"return (d.getMonth() + 1).zf(2);
            case "dd"return d.getDate().zf(2);
            case "E"return weekName[d.getDay()];
            case "HH"return d.getHours().zf(2);
            case "hh"return ((h = d.getHours() % 12) ? h : 12).zf(2);
            case "mm"return d.getMinutes().zf(2);
            case "ss"return d.getSeconds().zf(2);
            case "ms"return d.getMilliseconds().zf(3);
            case "a/p"return d.getHours() < 12 ? "오전" : "오후";
            defaultreturn $1;
        }
    });
};
  
String.prototype.string = function(len){var s = '', i = 0while (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);};
 
//사용방법
 
new Date("2021-10-11 11:22:33").format("yyyy-MM-dd HH:mm:ss");
  
<!-- 결과 -->
2021-10-11 11:22:33
 
 
 
cs

 

출처 : https://stove99.tistory.com/46