30장 Date
- 생성자 함수
- 표시되는 시간은 JS 코드가 실행된 시스템의 시간 기준
1. Date 생성자 함수
- Date 생성자 함수로 생성한 Date 객체는 기본적으로 현재 날짜와 시간을 나타내는 정수값을 가진다.
- 다른 날짜를 다루려면 생성자 함수에 인수를 주면 된다.
- Date 생성자 함수로 객체를 생성하는 방법은 다음과 같이 4가지가 있다.
1.1 new Date()
new Date();
Date();
const dateObj = new Date();
console.log(dateObj.toString());
1.2 new Date(milliseconds)
- 숫자 전달
- 1970/1/1 00:00:00(UTC)에 milliseconds 만큼 더한 Date 객체를 반환
new Date(0);
new Date(86400000);
1.3 new Date(dateString)
- 문자열 전달
- 지정된 날짜와 시간을 나타내는 Date 객체 반환
- 문자열은 Date.parse 메서드로 해석 가능한 형식이어야 한다.
new Date('May 26, 2020 10:00:00');
new Date('2020/03/26/10:00:00');
1.4 New Date(year, month[,day, hour, minute, second, millisecond])
- 여러 숫자 인수 전달
- 연, 월은 반드시 지정해야 하며, 지정하지 않은 옵션 정보는 0 또는 1로 초기화 된다
| 인수 | 내용 |
|---|
| year | 연을 나타내는 1900년 이후의 정수, 0~99는 1900~1999로 처리 |
| month | 월을 나타내는 0~11 정수(zero base🤬) |
| day | 일을 나타내는 1~31 정수 |
| hour | 시를 나타내는 0~23 정수 |
| minute | 분을 나타내는 0~59 정수 |
| second | 초를 나타내는 0~59 정수 |
| millisecond | 밀리초를 나타내는 0~999 정수 |
new Date(2020, 2);
new Date(2020, 2, 26, 10, 00, 00, 0);
new Date('2020/3/26/10:00:00:00');
2. Date 메서드
2.1 Date.now
- 1970/1/1 00:00:00(UTC)을 기준으로 경과한 시간을 milliseconds 숫자로 반환
const now = Date.now();
console.log(now);
new Date(now);
2.2 Date.parse
- 1970/1/1 00:00:00(UTC)을 기준으로 인자로 전달한 지정시간까지의 밀리초를 숫자로 반환
Date.parse('Jan 2, 1970 00:00:00 UTC');
Date.parse('Jan 2, 1970 09:00:00');
Date.parse('1970/01/02/09:00:00');
2.3 Date.UTC
- 1970/1/1 00:00:00(UTC)을 기준으로 인자로 전달한 지정시간까지의 밀리초를 숫자로 반환
- 이 때 인자는 (year, month[,day, hour, minute, second, millisecond]) 여야 함
- 무조건 UTC로 인식
- 월은 0부터 시작..
Date.UTC(1970,0,2);
Date.UTC('1970/1/2');
2.4 Date.prototype.getFullYear
new Date('2020/07/24').getFullYear();
2.5 Date.prototype.setFullYear
- Date 객체의 연도를 나타내는 정수 설정
- 옵셥으로 월, 일도 설정 가능
const today = new Date();
today.setFullYear(2000);
today.getFullYear();
today.setFullYear(1900,0,1);
today.getFullYear();
2.6 Date.prototype.getMonth
- Date 객체의 월을 나타내는 정수 반환
- 0은 1월
new Date('2020/07/24').getMonth();
2.7 Date.prototype.setMonth
- Date 객체의 월을 나타내는 정수 설정
- 옵션으로 일도 설정 가능
const today = new Date();
today.setMonth(0);
today.getMonth();
today.setMonth(11,1);
today.getMonth();
2.8 Date.prototype.getDate
new Date('2020/07/24').getDate();
2.9 Date.prototype.setDate
const today = new Date();
today.setDate(1);
today.getDate();
2.10 Date.prototype.getDay
- Date 객체의 요일을 나타내는 정수를 반환
- 일요일 : 0
- 토요일 : 6
new Date('2022/11/20').getDay();
2.11 Date.prototype.getHours
new Date('2022/11/20/12:00').getHours();
2.12 Date.prototype.setHours
- Date 객체의 시간 설정
- 옵션으로 분, 초, 밀리초 설정 가능
const today = new Date();
today.setHours(7);
today.getHours();
today.setHours(0,0,0,0);
today.getHours();
2.13 Date.prototype.getMinutes
new Date('2022/11/20/12:30').getMinutes();
2.14 Date.prototype.setMinutes
- Date 객체의 분 설정
- 옵션으로 초, 밀리초 설정 가능
const today = new Date();
today.setMinutes(50);
today.getMinutes();
today.setMinutes(5, 10, 999);
today.getMinutes();
2.15 Date.prototype.getSeconds
new Date('2022/11/20/12:30').getSeconds();
2.16 Date.prototype.setSeconds
- Date 객체의 초 설정
- 옵션으로 밀리초 설정 가능
const today = new Date();
today.setSeconds(30);
today.getSeconds();
today.setSeconds(10, 0);
today.getSeconds();
2.17 Date.prototype.getMilliSeconds
new Date('2022/11/20/12:30:10:150').getMilliSeconds();
2.18 Date.prototype.setMilliSeconds
- Date 객체의 초 설정
- 옵션으로 밀리초 설정 가능
const today = new Date();
today.setMilliSeconds(123);
today.getMilliSeconds();
2.19 Date.prototype.getTime
- 1970/1/1 00:00:00(UTC)을 기준으로 Date 객체 시간까지의 밀리초 반환
new Date('2020/07/24/12:30').getTime();
2.20 Date.prototype.setTime
- 1970/1/1 00:00:00(UTC)을 기준으로 Date 객체 시간까지의 밀리초 설정
const today = new Date();
today.setTime(86400000);
console.log(today);
2.21 Date.prototype.getTimezoneOffset
- UTC와 Date 객체에 지정된 locale 시간과의 차이를 분 단위로 반환
- UTC = KST - 9h
const today = new Date();
today.getTimezoneOffset() / 60;
2.23 Date.prototype.toDateString
- 사람이 읽을 수 있는 형식의 문자열로 Date 객체의 날짜를 반환
const today = new Date('2020/7/24/12:30');
today.toString();
today.toDateString();
2.23 Date.prototype.toTimeString
- 사람이 읽을 수 있는 형식의 문자열로 Date 객체의 시간을 반환
const today = new Date('2020/7/24/12:30');
today.toString();
today.toTimeString();
2.24 Date.prototype.toISOString
- ISO 8601 형식의 문자열로 Date 객체의 날짜와 시간을 반환
const today = new Date('2020/7/24/12:30');
today.toString();
today.toISOString();
today.toISOString().slice(0, 10);
today.toISOString().slice(0, 10).replace(/-/g, '');
2.25 Date.prototype.toLocaleString
- 인수로 전달한 로케일을 기준으로 Date 객체의 날짜와 시간을 표현한 문자열을 반환
- 인자 생략 시 브라우저가 동작 중인 시스템의 locale 적용
const today = new Date('2020/7/24/12:30');
today.toString();
today.toLocaleString();
today.toLocaleString('ko-KR');
today.toLocaleString('en-US');
today.toLocaleString('ja-JP');
2.26 Date.prototype.toLacaleTimeString
- 인수로 전달한 locale을 기준으로 Date 객체의 시간을 표현한 문자열 반환
- 인자 생략 시 브라우저가 동작 중인 시스템의 locale 적용
const today = new Date('2020/7/24/12:30');
today.toString();
today.toLocaleTimeString();
today.toLocaleTimeString('ko-KR');
today.toLocaleTimeString('en-US');
today.toLocaleTimeString('ja-JP');
3. Date를 활용한 시계 예제
- 현재 날짜와 시간을 초 단위로 반복 출력하는 코드
(function printNow() {
const today = new Date();
const dayNames = [
'(일요일)',
'(월요일)',
'(화요일)',
'(수요일)',
'(목요일)',
'(금요일)',
'(토요일)'
];
const day = dayNames[today.getDay()];
const year = today.getFullYear();
const month = today.getMonth() + 1;
const date = today.getDate();
let hour = today.getHours();
let minute = today.getMinutes();
let second = today.getSeconds();
const ampm = hour >= 12 ? 'PM' : 'AM';
hour %= 12;
hour = hour || 12;
minute = minute < 10 ? '0' + minute : minute;
second = second < 10 ? '0' + second : second;
const now = `${year}년 ${month}월 ${date}일 ${day} ${hour}:${minute}:${second} ${ampm}`;
console.log(now);
setTimeout(printNow, 1000);
}());