자바스크립트에서는 내장 Date 객체를 사용해 다양한 형식의 날짜를 손쉽게 생성하고 표시할 수 있습니다. new Date() 생성자에 날짜 문자열을 전달하면, 자바스크립트가 해당 문자열을 해석하여 날짜 객체로 변환해 줍니다.
예제 코드
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<style>
body {
font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
}
.sample {
font-size: 18px;
font-weight: 500;
}
</style>
</head>
<body>
<h1>Date Format</h1>
<div class="sample"></div>
<button class="Btn">CLICK HERE</button>
<h3>Click on the above button to see the different date formats</h3>
<script>
let fillEle = document.querySelector(".sample");
let date = [];
date.push(new Date('2020-01-20'));
date.push(new Date('2020-02'));
date.push(new Date('2020'));
date.push(new Date("2015-03-25T12:00:00Z"));
fillEle.innerHTML = date + '<br>';
document.querySelector(".Btn").addEventListener("click", () => {
date.forEach(item=>{
fillEle.innerHTML += item + '<br>'
})
});
</script>
</body>
</html>코드 설명
위 예제에서는 네 가지 서로 다른 형식의 날짜 문자열을 Date 객체에 전달했습니다.
'2020-01-20': 연도-월-일 순서의 ISO 8601 기본 형식'2020-02': 연도와 월만 지정한 형식'2020': 연도만 지정한 형식"2015-03-25T12:00:00Z": 시간과 UTC 표준시(Z)까지 포함된 ISO 8601 확장 형식
페이지가 로드되면 배열에 담긴 각 날짜 객체가 브라우저의 기본 날짜 표기 형식으로 자동 변환되어 화면에 출력됩니다. 이후 "CLICK HERE" 버튼을 클릭하면 forEach() 메서드를 통해 각 날짜가 한 줄씩 다시 나타납니다.
실행 결과

"CLICK HERE" 버튼을 클릭하면 −
