티스토리 툴바


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


Example!
//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"));
저작자 표시 비영리 변경 금지
트랙백 0 Comment 3
  1. 양해준 2012/02/20 11:34 address edit & del reply

    잘 봤습니다 ~ 많이 도움되네요 ^^

  2. 스토브 2012/02/20 15:37 address edit & del reply

    도움이 되셨다니~ 저의 기쁨이에요~

  3. hfgh 2012/05/11 11:01 address edit & del reply

    v

prev 1 ... 73 74 75 76 77 78 79 80 81 ... 122 next