본문 바로가기

FRONT

[JavaScript 자바스크립트] - 현재 날짜, 시간 가져오기

728x90

1. Date 객체 생성

const date = new Date();

console.log('Date.toString(): ' + date.toString());
console.log('Date.toUTCString(): ' + date.toUTCString());

//Date.toString(): Sat Apr 02 2022 09:58:09 GMT+0900 (Korean Standard Time)
//Date.toUTCString(): Sat, 02 Apr 2022 00:58:09 GMT

 

 

1) Locale String

기본적으로 toString()은 영어로 출력하므로,

어떤 국가/언어에서 사용하는 형식으로 출력하고 싶을 때는 toLocaleString(Locale)으로 문자열을 출력

const date = new Date();
console.log('locale string: ' + date.toLocaleString());
console.log('locale string(ko-kr): ' + date.toLocaleString('ko-kr'));
console.log('locale string(en-us): ' + date.toLocaleString('en-us'));

//locale string: 4/2/2022, 10:02:54 AM
//locale string(ko-kr): 2022. 4. 2. 오전 10:02:54
//locale string(en-us): 4/2/2022, 10:02:54 AM

 

 

2) 년, 월, 일 정보 가져오기 (날짜)

getMonth() : 0 ~ 11 범위의 값으로 리턴하는데, 0이 1월이고, 11이 12월을 의미

const date = new Date();

const year = date.getFullYear();
const month = date.getMonth() + 1;
const day = date.getDate();

console.log('date: ' + date.toLocaleDateString('ko-kr'));
console.log('year: ' + year);
console.log('month: ' + month);
console.log('day: ' + day);

//date: 2022. 4. 2.
//year: 2022
//month: 4
//day: 2

 

 

3) 시간, 분, 초 정보 가져오기 (시간)

const date = new Date();

const hours = date.getHours();
const minutes = date.getMinutes();
const seconds = date.getSeconds();
const milliseconds = date.getMilliseconds();

console.log('time: ' + date.toLocaleTimeString('ko-kr'));
console.log('hours: ' + hours);
console.log('minutes: ' + minutes);
console.log('seconds: ' + seconds);
console.log('milliseconds: ' + milliseconds);

//time: 오전 10:10:15
//hours: 10
//minutes: 10
//seconds: 15
//milliseconds: 760

 

 

4) "2022-09-23" 와 같은 날짜 포맷 가져오기

const date = new Date();

const year = date.getFullYear();
const month = ('0' + (date.getMonth() + 1)).slice(-2);
const day = ('0' + date.getDate()).slice(-2);
const dateStr = year + '-' + month + '-' + day;

console.log(dateStr);

//2022-04-02

 

 

5) "10:33:22" 와 같은 시간 포맷 가져오기

const date = new Date();

const hours = ('0' + date.getHours()).slice(-2);
const minutes = ('0' + date.getMinutes()).slice(-2);
const seconds = ('0' + date.getSeconds()).slice(-2);
const timeStr = hours + ':' + minutes + ':' + seconds;

console.log(timeStr);

//10:33:22

 

 

 

728x90