날짜 포맷 변환

sky (polyjean)·2023년 1월 9일
0

Studies

목록 보기
2/10

https://electronic-moongchi.tistory.com/83

시간 날짜 받기 스크립트 필요해서 구글 검색했다.
참고해서 커스터마이징, 이럴때 프로토타입 쓰는구나.

  // 날짜 포맷 변환 
  Date.prototype.format = function (f) {
    if (!this.valueOf()) return " ";
    const weekKorShortName = ["일", "월", "화", "수", "목", "금", "토"]
    let d = this;

    return f.replace(/(yyyy|MM|dd|ww|HH|hh|mm|a\/p)/gi, function ($1) {
      switch ($1) {
        case "yyyy": return d.getFullYear(); // 년 (4자리)
        case "MM": return (d.getMonth() + 1); // 월
        case "dd": return d.getDate(); // 일
        case "ww": return weekKorShortName[d.getDay()]; // 요일 (짧은 한글)
        case "HH": return d.getHours(); // 시간
        case "hh": return ((h = d.getHours() % 12) ? h : 12).zf(2); // 시간 (12시간 기준, 2자리)
        case "mm": return d.getMinutes().zf(2); // 분 (2자리)
        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); };
profile
front end developer

0개의 댓글