본문 바로가기

JavaScript

18. Date 객체

Date 객체
  • 날짜, 시간 등을 쉽게 처리할 수 있는 내장 객체
연도(year)
  • 2자리로 연도를 표기: 1900년 ~ 1999년
  • 4자리로 연도를 표기: 2000년 ~
월(month)
  • 0 ~ 11, 0(1월), 11(12월)
Date 객체를 생성하는 방법
new Date()
  • 현재 날짜 시간을 저장한 객체가 생성
console.log(new Date());
// Fri Apr 07 2023 13:01:20 GMT+0900 (한국 표준시)
new Date('날짜 문자열)
  • 해당 특정 날짜와 시간을 저장한 객체가 생성
// 년도를 2자리로 설정하면 1900년
console.log(new Date(23,4,6));
// Sun May 06 1923 00:00:00 GMT+0900 (한국 표준시)
new Date(밀리초)
  • 1970년 1월 1일 0시 0분 0초를 기준으로 해당 밀리초 만큼 지난 날짜와 시간을 저장한 객체가 생성
const date = new Date(1000000000000);
// Sun Sep 09 2001 10:46:40 GMT+0900 (한국 표준시)
new Date(년, 월, 일, 시, 분, 초, 밀리초)
  • 해당 날짜와 시간을 저장한 객체가 생성
const current_time = new Date(2023, 3, 6, 14, 44, 0);
console.log(current_time);
// Thu Apr 06 2023 14:44:00 GMT+0900 (한국 표준시)
Date 객체 메소드
getFullYear()
  • 연도를 가져오는 메소드
getMonth()
  • 달을 가져오는 메소드
  • 1월 = 0, 12월 = 11
getDate()
  • 일을 가져오는 메소드
  • 월요일 = 0, 일요일 = 6
getDay
  • 요일을 가져오는 메소드
getHours()
  • 시간을 가져오는 메소드
getMinutes()
  • 분을 가져오는 메소드
getSeconds()
  • 초를 가져오는 메소드
getMilliseconds()
  • 밀리초를 가져오는 메소드
Date 객체 예제
const current_time = new Date(2023, 3, 6, 14, 44, 0);

console.log(`현재 연도: ${current_time.getFullYear()}`); // 현재 연도: 2023
console.log(`현재 월: ${current_time.getMonth()+1}`); // 현재 월: 4
console.log(`현재 일: ${current_time.getDate()}`); // 현재 일: 6
console.log(`현재 요일: ${current_time.getDay()}`); // 현재 요일: 4
console.log(`현재 시간: ${current_time.getHours()}`); // 현재 시간: 14
console.log(`현재 분: ${current_time.getMinutes()}`); // 현재 분: 44
console.log(`현재 초: ${current_time.getSeconds()}`); // 현재 초: 0
console.log(`현재 밀리초: ${current_time.getMilliseconds()}`); // 현재 밀리초: 0

'JavaScript' 카테고리의 다른 글

20. form 객체  (0) 2023.04.07
19. window 객체  (0) 2023.04.07
17. String 객체  (0) 2023.04.07
16. Math 객체  (0) 2023.04.07
15. 프로토타입(prototype)  (0) 2023.04.07