JavaScript
Date 객체에 날짜 포맷 함수 추가
최성헌
2017. 7. 6. 14:30
Java의 SimpleDateFormat 과 유사한 format 형태로 javascript의 Date 객체를 이용하도록 하는 예제.
<script language="JavaScript">
/** 문자나 숫자의 길이가 매개변수인 len 값보다 작을 경우 앞에 '0' 을 붙힌다. **/
String.prototype.zf = function(len){return "0".string(len - this.length) + this;};
Number.prototype.zf = function(len){return this.toString().zf(len);};
String.prototype.string = function(len){var s = '', i = 0; while (i++ < len) { s += this; } return s;};
/** 매개변수로 날짜 포맷을 전달 받아 해당 포맷 형태로 문자열을 반환 한다. **/
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;
}
});
};
var nowDate = new Date();
console.log(nowDate.format("yyyy-MM-dd HH:mm:ss"));
console.log(nowDate.format("yy-MM-dd HH:mm:ss"));
console.log(nowDate.format("yyyy-MM-dd a/p hh:mm:ss E"));
</script>
출력 결과
[Log] 2017-07-06 14:26:40 (localhost, line 39)
[Log] 17-07-06 14:26:40 (localhost, line 40)
[Log] 2017-07-06 오후 02:26:40 목요일 (localhost, line 41)