(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
(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, 금요일이므로
'[Javascript]' 카테고리의 다른 글
[javascript] event 객체의 매개변수와 property (0) | 2023.03.25 |
---|---|
[javascript] Event의 구성요소와 등록방법 (0) | 2023.03.25 |
[Javascript] (1)firstChild와 firstElementChild (2)createTextNode와 innerHTML 그리고 textContent (3)Node와 Element (0) | 2023.03.17 |
[Javascript] createElement, forEach, innerHTML, append 활용 예시 (0) | 2023.03.16 |
[Javascript] JS로 HTML 요소 생성 및 추가하기 (0) | 2023.03.16 |