C# 을 사용 할 시 DateTime 객체를 날짜포맷 으로 처리하는것이 굉장히 편리했는데 Java 나 JavaScript 를 보면 뭔가 포맷을 맞추기 위해 할일이 어수선 합니다.
요즘 JavaScript 모듈화 하는 재미에 푹 빠져서 Date 관련 유틸 Class 를 만들어 보려고 하면서 여러 블로그를 찾아 보았으나 이렇다할 좋은 자료를 보지 못하다가..
구경 가본 블로그 : https://annotations.tistory.com/92
날짜 관련 유틸리티 함수 제작 (유틸제작 1편)
날짜 관련 유틸리티 함수 제작 (유틸제작 1편) 포스팅의 제목과 같이 JavaScript 에서 Date 객체를 이용한 함수 제작을 설명드리려고 합니다. Date 객체 많이들 사용하실텐데 미리 관련 함수를 만들어
annotations.tistory.com
필요한 포맷에 따라 모든 메서드를 만들어 둔 것을 보았습니다.
응용하면 전달된 포맷 (예 : yyyyMMdd , yyyy-MM-dd, yyyy/MM/dd HH:mm.ss, MM/dd/yyyy) 대부분의 포맥을 모두 만족 시킬 수 있는 1개의 메서드로 가능 할 듯 하여 위 블로그님의 코드를 보고 아래처럼 변형해 보았습니다.
클래스
export class DateTime {
constructor() {
console.log('## constructor => Date');
}
// 포맷 적용 메서드
#getApplyFormat(date, format) {
var month = (date.getMonth() + 1);
var day = date.getDate();
var hrs = date.getHours();
var min = date.getMinutes()
var sec = date.getSeconds();
if(Number(month) < 10){ month = "0" + month; }
if(Number(day) < 10){ day = "0" + day; }
if(Number(hrs) < 10){ hrs = "0" + hrs; }
if(Number(min) < 10){ min = "0" + min; }
if(Number(sec) < 10){ sec = "0" + sec; }
format = format.toUpperCase().replace('YYYY', `${"" + date.getFullYear()}`);
format = format.toUpperCase().replace('MM', `${month}`);
format = format.toUpperCase().replace('DD', `${day}`);
format = format.toUpperCase().replace('HH', `${hrs}`);
format = format.toUpperCase().replace('MM', `${min}`);
format = format.toUpperCase().replace('SS', `${sec}`);
return format;
}
// 현재 날짜를 포맷에 맞춰주는 메서드
getCurrentFormatDate(format) {
return this.#getApplyFormat(new Date, format);
}
// 전달된 날짜를 포맷에 맞춰주는 메서드
getFormatDate(date, format) {
return this.#getApplyFormat(date, format);
}
}
사용방법
<script type="module">
import {DateTime} from '/js/datetime.js';
$(function () {
let date = new DateTime();
console.log(date.getCurrentFormatDate('yyyy-MM-dd HH:mm.ss')));
});
</script>
이글을 보시는 다른 블로거 님들이 더 나은 클래스로 발전 시켜 주시기를 빌며~
'JavaScript' 카테고리의 다른 글
| JavaScript 에서 POST 호출 하는 방법 (0) | 2023.12.05 |
|---|---|
| JavaScript 에서 JSON 문자열 이쁘게 출력하기 (0) | 2023.12.05 |