aotoyae

[JS] Date() 데이트 객체, 날짜 가져오기 본문

JavaScript

[JS] Date() 데이트 객체, 날짜 가져오기

aotoyae 2024. 1. 2. 14:55

 

 

: 날짜를 이용하는 내장 객체

💡 괄호 비워두기

우선 변수를 생성한 순간의 날짜, 시간을 가져올 수 있다.

let myDate = new Date();

console.log(myDate);
//Tue Jan 02 2024 12:48:12 GMT+0900 (한국 표준시)

 

💡 문자열 넣어주기

특정 날짜의 객체를 만들 수 있다.

시간을 지정하고 싶다면 대문자 T 뒤 시간 입력, 시간을 지정하지 않으면 자정을 기준으로 객체가 생성된다!

let myBirthday = new Date("2024-01-02");
let myBirthday2 = new Date("2024-01-02T08:08:08");

console.log(myBirthday)
console.log(myBirthday2)

// Mon Jan 02 2024 09:00:00 GMT+0900 (한국 표준시)
// Mon Jan 02 2024 08:08:08 GMT+0900 (한국 표준시)

 

💡 괄호 안에 여러 개의 값 전달하기

new Date(YYYY, MM, DD, hh, mm, ss, ms)

연도와 월까지가 필수! 뒤의 값들은 생략하면 1일 0시 0분 0초 0밀리초로 처리된다.

❗️주의) month의 경우만 시작 숫자가 0이다! 1을 입력하면 2월로 객체 생성

let myDay = new Date(2024, 1, 02);

console.log(myDay);
// Thu Feb 02 2024 00:00:00 GMT+0900 (한국 표준시)

 

💡 Time stamp 타임 스탬프

데이트 객체의 기준 날짜, 1970년 1월 1일 00:00:00 UTC 부터 지금까지 경과한 시간의 정수값

현재 시간에 대한 Time stamp : Date.now(), Date.getTime()

 

💡 getTime() 등 여러 메소드들

날짜, 시간을 가져오거나 두 시간 사이의 차이도 계산할 수 있다.

let lastChristmas = new Date(2023, 11, 25, 8, 13, 25);
let today = new Date();

let timeDiff = today.getTime() - lastChristmas.getTime();
console.log(Math.floor(timeDiff / 1000 / 60 / 60) + " 시간"); // "198 시간"

console.log(lastChristmas.getFullYear()); // 2023
console.log(lastChristmas.getMonth()); // 11
console.log(lastChristmas.getDate()); // 25 : 일자
console.log(lastChristmas.getDay()); // 1 : 요일 (일요일부터 0 ~ 6)
console.log(lastChristmas.getHours()); // 8
console.log(lastChristmas.getMinutes()); // 13
console.log(lastChristmas.getSeconds()); // 25
console.log(lastChristmas.getMilliseconds()); // 0

 

➕ 지정해 둔 날짜를 수정하고 싶을 땐 set으로 시작하는 메소드 활용!

setFullYear(), setMonth, setDate, setHours,,,

setTime(milliseconds)(1970년 1월 1일 00:00:00 UTC부터 밀리초 이후를 나타내는 날짜를 설정)

 

➕ 계산 활용~

let today = new Date(2024, 1, 2);
let tomorrow = new Date(2024, 1, 3);

let timeDiff = tomorrow - today;
console.log(timeDiff); // 86400000 (ms)
console.log(timeDiff / 1000); // 86400 (sec)
console.log(timeDiff / 1000 / 60); // 1440 (min)
console.log(timeDiff / 1000 / 60 / 60); // 24 (hour)
console.log(timeDiff / 1000 / 60 / 60 / 24); // 1 (date)

 

💡 계산 없이 간단하게 시간 정보 알아내기

console.log(today.toLocaleDateString()); // "2024. 1. 2." (년. 월. 일)
console.log(today.toLocaleTimeString()); // "오후 2:37:05" (시:분:초)
console.log(today.toLocaleString()); // "2024. 1. 2. 오후 2:37:05" (년. 월. 일 시:분:초)

 

💡 없는 날짜를 작성하면 자동으로 수정한다!

1월 32일을 입력하니 2월 1일이 출력된다.

let oneday = new Date(2023, 0, 32);
console.log(oneday); // Wed Feb 01 2023 00:00:00 GMT+0900 (한국 표준시)

 

💡 Date.now()

: 이 메소드가 호출된 시점의 타임 스탬프를 반환한다.

새 객체를 만들지 않아도 바로 현 시점의 날짜 값을 얻어낼 수 있는 것! (코드를 한 줄 줄일 수 있다!)

그래서 특정한 시점이 아니라 단순히 순간순간 그 때 당시 시간 값이 필요한 경우

Date.now() 메소드를 활용하는 것이 가독성도 좋고 성능적인 측면에서도 좀 더 유리하다.

let myNow = new Date();
console.log(Date.now() === myNow.getTime()); // true