Notice
Recent Posts
Recent Comments
Link
«   2024/05   »
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
관리 메뉴

UpDown Dev Story

Javascript Date Format 함수 본문

Etc

Javascript Date Format 함수

updown 2018. 3. 27. 16:28

Javascript Date Format 함수


아래 처럼 넣어준다


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|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 "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);};

실재 사용 하는 방법


//2011 09 11일 오후 03 45 42
console.log(new Date().format("yyyy MM dd a/p hh mm ss"));

//2011-09-11
console.log(new Date().format("yyyy-MM-dd"));

//'11 09.11
console.log(new Date().format("'yy MM.dd"));

//2011-09-11 일요일
console.log(new Date().format("yyyy-MM-dd E"));

//현재년도 : 2011

console.log("현재년도 : " + new Date().format("yyyy"));



'Etc' 카테고리의 다른 글

Enum 클래스 사용 시 성능 향상 방법  (1) 2024.01.10
IntelliJ 자동 import 정리 설정  (0) 2024.01.05
Node.js 시작하기  (0) 2020.01.31
Comments