[Javascript]

[Javascript] Date() 관련 참고할 만한 사항

개발잘하고싶음 2023. 3. 22. 21:14

(1)Date()와 new Date() 차이

①Date() 

new 키워드가 없는 Date() 함수는 인수를 무시하며, 현재 날짜 및 시간을 나타내는 문자열을 반환합니다.

Date('asd')
// 'Wed Dec 22 2021 19:58:27 GMT+0900 (한국 표준시)'

Date()
// 'Wed Dec 22 2021 19:59:10 GMT+0900 (한국 표준시)'

typeof Date()
// 'string'

참고로 date()로 하면 안 된다. Date()다.

let a = date();
console.log(a); // Uncaught ReferenceError: date is not defined

 

객체가 아니므로 getMonth() 등 메소드 사용할 수 없음.

 let currentDay = Date();
 yearMonth.textContent= currentDay.getMonth();
  
 //Uncaught TypeError: currentDay.getMonth is not a function

 

②new Date()

new 키워드를 사용한 new Date()는 Date 타입인 새로운 객체를 생성합니다. 인수를 생략하면 현재 날짜 및 시간을 나타내는 Date 객체가 생성됩니다. 인자를 전달하면 인자 형태에 따라 Date 객체가 생성됩니다. 위와 달리 getMonth() 등 메소드를 사용할 수 있음.

new Date();
// Thu Dec 23 2021 00:24:26 GMT+0900 (한국 표준시)

new Date('2020-01-01');
// Wed Jan 01 2020 09:00:00 GMT+0900 (한국 표준시)

new Date(2021, 11, 23);
// Thu Dec 23 2021 00:00:00 GMT+0900 (한국 표준시)

new Date(2021, 11, 23, 12, 23, 00);
// Thu Dec 23 2021 12:23:00 GMT+0900 (한국 표준시)

typeof new Date()
// 'object'

 

③참고 URL

 

[JavaScript]Date와 new Date 차이점

이번 포스팅에서는 Date, Date(), new Date()의 차이점을 소개합니다. 목차 Date Date() new Date() Date ECMAScript의 타입에는 Date 타입이 존재하지 않으며, 아래 8개의 타입이 존재합니다. undefined null boolean string

developer-talk.tistory.com

 

(2)new Date(year,month,date)에서 date 인수를 0으로 할 경우

새로운 date 객체를 만들 때 date 인수의 값을 0으로 하면 마지막 날짜를 가진 date 객체가 반환된다. 참고로 getMonth()는 현재 date 객체의 월을 0~11 사이의 숫자로 반환한다.

var startDay = new Date(2023, 3, 0);  //'2023-03-31'을 뜻함
var Month = startDay.getMonth(); //month-1 
var Date = startDay.getDate();// 0은 마지막 날을 뜻함.
var Day = startDay.getDay(); // 일요일부터 0

console.log(Month); // 2
console.log(Date); // 31
console.log(Day); // 5, 금요일이므로