[JavaScript] Date

김서진·2024년 2월 24일
post-thumbnail

Date

Date 객체는 자바스크립트에서 날짜와 시간을 다룰 수 있는 객체.
현재 날짜와 시간을 얻거나 특정 날짜와 시간을 생성하고 여러 메서드를 사용하여 날짜와 시간을 다양한 형식으로 표시할 수 있다.

Date 객체 생성

// 현재 날짜와 시간을 나타내는 객체 생성
const currentDate = new Date();

// 특정 날짜와 시간을 나타내는 객체 생성 (년, 월, 일, 시, 분, 초 순서)
// new Date(year, monthIndex, day, hours, minutes, seconds);
const specificDate = new Date(2022, 0, 1, 12, 0, 0);

월은 0부터 시작

Date 객체는 비교 연산자로 직접 비교할 수 있다

const date1 = new Date(2024, 0, 1);
const date2 = new Date(2024, 0, 2);

if (date1 < date2) {
    console.log("date1이 date2보다 빠릅니다.");
} else if (date1 > date2) {
    console.log("date1이 date2보다 늦습니다.");
} else {
    console.log("date1과 date2는 같습니다.");
}

배열을 사용해도 Date 객체를 생성할 수 있다

const dateArray = [2022, 0, 1]; // [연도, 월, 일]
const dateFromArr = new Date(...dateArray); // 배열의 각 요소를 개별적인 인자로 전달

console.log(dateFromArr);

주요 메서드

1. getDate(), getMonth(), getFullYear(), getTime()

const day = currentDate.getDate();      // 현재 날짜

const month = currentDate.getMonth();   // 현재 월 (0부터 시작)

const year = currentDate.getFullYear(); // 현재 연도

const timestamp = currentDate.getTime(); // 1970년 1월 1일 00:00:00 UTC부터 경과된 밀리초

2. getHours(), getMinutes(), getSeconds(), getDay()

const hours = currentDate.getHours();      // 현재 시간 (24시간제)

const minutes = currentDate.getMinutes();  // 현재 분

const seconds = currentDate.getSeconds();  // 현재 초

const day = currentDate.getDay(); // 일요일(0)부터 토요일(6)까지의 현재 값

3. toLocaleString()

const LocalDate = currentDate.toLocaleString(); // 지역에 맞는 날짜와 시간 형식으로 변환

참고자료

0개의 댓글