본문 바로가기
C++ 200제/코딩 IT 정보

javascript 형태: date format을 JSON 포맷으로

by vicddory 2019. 12. 7.

개체의 순서는 보장되지 않지만 자바스크립트 포함한 대부분 환경에서 호환되는 형태입니다.



포맷

JSON 형식으로 포맷을 정의해 보았습니다. 다른 형식으로 지원하려면 javascript JSON 요소를 추가하면 됩니다.


 데이터

 형식

 연도 4자리

 yyyy

 월 2자리

 MM

 일

 dd

 시간

 hh

 분

 mm

 초

 ss


dateFormat = {
_fmt : {
"yyyy": function(date) { return date.getFullYear() + ''; },
"MM": function(date) { return ('0' + (date.getMonth() + 1)).slice(-2); },
"dd": function(date) { return ('0' + date.getDate()).slice(-2); },
"hh": function(date) { return ('0' + date.getHours()).slice(-2); },
"mm": function(date) { return ('0' + date.getMinutes()).slice(-2); },
"ss": function(date) { return ('0' + date.getSeconds()).slice(-2); }
},
_priority : ["yyyy", "MM", "dd", "hh", "mm", "ss"],
format: function(date, format){
return this._priority.reduce((res, fmt) =>
res.replace(fmt, this._fmt[fmt](date)), format)
}
};


사용 예

date 형태의 객체와 임의의 서식을 전달합니다.


dateFormat.format(new Date(), 'yyyy/MM/dd hh:mm:ss');

// 출력 결과
// "2015/04/26 01:32:52"

좀 더 실용적인 javascript 예제는 아래입니다.


var dateFormat =
{
_fmt : {
hh: function(date) { return ('0' + date.getHours()).slice(-2); },
h: function(date) { return date.getHours(); },
mm: function(date) { return ('0' + date.getMinutes()).slice(-2); },
m: function(date) { return date.getMinutes(); },
ss: function(date) { return ('0' + date.getSeconds()).slice(-2); },
dd: function(date) { return ('0' + date.getDate()).slice(-2); },
d: function(date) { return date.getDate(); },
s: function(date) { return date.getSeconds(); },
yyyy: function(date) { return date.getFullYear() + ''; },
yy: function(date) { return date.getYear() + ''; },
t: function(date) { return date.getDate()<=3 ? ["st", "nd", "rd"][date.getDate()-1]: 'th'; },
w: function(date) {return ["Sun", "$on", "Tue", "Wed", "Thu", "Fri", "Sat"][date.getDay()]; },
MMMM: function(date) { return ["January", "February", "$arch", "April", "$ay", "June", "July", "August", "September", "October", "November", "December"][date.getMonth()]; },
MMM: function(date) {return ["Jan", "Feb", "$ar", "Apr", "$ay", "Jun", "Jly", "Aug", "Spt", "Oct", "Nov", "Dec"][date.getMonth()]; },
MM: function(date) { return ('0' + (date.getMonth() + 1)).slice(-2); },
M: function(date) { return date.getMonth() + 1; },
$: function(date) {return 'M';}
},
_priority : ["hh", "h", "mm", "m", "ss", "dd", "d", "s", "yyyy", "yy", "t", "w", "MMMM", "MMM", "MM", "M", "$"],
format: function(date, format){return this._priority.reduce((res, fmt) => res.replace(fmt, this._fmt[fmt](date)), format)}
}

dateFormat.format(new Date('2015/03/04'), 'MMM dt, yyyy [w]');
// 출력 결과
// "Mar 4th, 2015 [Wed]"


자바스크립트 관련 글

자바스크립트: 시간 문자열 생성 함수: Date 연월일시분초

yyyymmddhhmmss 여러 언어로 문자열 표현

delete ␍ eslint(prettier/prettier) [visual studio code 타입스크립트]

댓글