๋กœ์ผ“๐Ÿพ
article thumbnail

์ž๋ฐ”์Šคํฌ๋ฆฝํŠธ์—์„œ ํ˜„์žฌ ๋‚ ์งœ ๋ฐ ์‹œ๊ฐ„์„ ๊ตฌํ•˜๊ธฐ ์œ„ํ•ด์„œ๋Š” Date ๊ฐ์ฒด๋ฅผ ์‚ฌ์šฉํ•˜๋ฉด ๋œ๋‹ค. Date ๊ฐ์ฒด๋ฅผ ์‚ฌ์šฉํ•˜์—ฌ ํ˜„์žฌ์˜ ๋‚ ์งœ๋ฅผ ์ถœ๋ ฅํ•˜๋ฉด YYYY-MM-DD์™€ ๊ฐ™์€ ํ˜•์‹์˜ ๋‚ ์งœ ํฌ๋งท์œผ๋กœ ์ถœ๋ ฅ๋˜์ง€ ์•Š๊ธฐ ๋•Œ๋ฌธ์—, Date ๊ฐ์ฒด์—์„œ ์ œ๊ณตํ•˜๋Š” ์ถ”์ถœ ํ•จ์ˆ˜๋ฅผ ์‚ฌ์šฉํ•˜์—ฌ ๋‚ ์งœ ํฌ๋งท์„ ๋ณ€ํ™˜ํ•˜๋Š” ์ž‘์—…์ด ์ถ”๊ฐ€์ ์œผ๋กœ ํ•„์š”ํ•˜๋‹ค.

 

ํ˜„์žฌ ๋‚ ์งœ, ์‹œ๊ฐ„ ๊ตฌํ•˜๊ธฐ

var today = new Date();

console.log(today);
// ๊ฒฐ๊ณผ : Sun May 30 2021 15:47:29 GMT+0900 (๋Œ€ํ•œ๋ฏผ๊ตญ ํ‘œ์ค€์‹œ)

 

// ๊ฒฐ๊ณผ : Sun May 30 2021 15:47:29 GMT+0900 (๋Œ€ํ•œ๋ฏผ๊ตญ ํ‘œ์ค€์‹œ)

 

Date ๊ฐ์ฒด๋ฅผ ์‚ฌ์šฉํ•˜์—ฌ ํ˜„์žฌ ์‹œ์Šคํ…œ์˜ ๋‚ ์งœ๋ฅผ ๊ฐ€์ ธ์™€์„œ ์ถœ๋ ฅํ•˜๋ฉด, ํ‰์ƒ์‹œ์— ์‚ฌ์šฉํ•˜๋Š” ๋‚ ์งœ ํฌ๋งท(YYYY-MM-DD HH:MM:SS)๋กœ ์ถœ๋ ฅ๋˜์ง€ ์•Š๊ธฐ ๋•Œ๋ฌธ์— ์•„๋ž˜์˜ ์ถ”์ถœ ํ•จ์ˆ˜๋ฅผ ์‚ฌ์šฉํ•˜์—ฌ ๋‚ ์งœ ํฌ๋งท์„ ๋ณ€ํ™˜ํ•ด์•ผ ํ•œ๋‹ค.

 

๋‚ ์งœ ํฌ๋งท ๋ณ€๊ฒฝํ•˜๊ธฐ (YYYY-MM-DD)

var today = new Date();

var year = today.getFullYear();
var month = ('0' + (today.getMonth() + 1)).slice(-2);
var day = ('0' + today.getDate()).slice(-2);

var dateString = year + '-' + month  + '-' + day;

console.log(dateString);
// ๊ฒฐ๊ณผ : 2021-05-30

 

// ๊ฒฐ๊ณผ : 2021-05-30

 

๋‚ ์งœ ์ถ”์ถœ ํ•จ์ˆ˜๋ฅผ ์‚ฌ์šฉํ• ๋•Œ ์ฃผ์˜ํ•ด์•ผ ํ•  ์ ์€ getMonth() ํ•จ์ˆ˜์ธ๋ฐ, getMonth() ํ•จ์ˆ˜๋Š” 0~11์„ ๋ฐ˜ํ™˜ํ•˜๊ธฐ ๋•Œ๋ฌธ์— ํ•ญ์ƒ +1์„ ํ•ด์ค˜์•ผํ•œ๋‹ค. ๊ทธ๋ฆฌ๊ณ  getMonth(), getDate() ํ•จ์ˆ˜๋Š” ์ˆ˜์น˜ ๊ฐ’์„ ๋ฐ˜ํ™˜ํ•˜๊ธฐ ๋•Œ๋ฌธ์— 2์ž๋ฆฌ๋ฅผ ๋งž์ถ”๊ธฐ ์œ„ํ•ด์„œ๋Š” "0"์„ ๋ถ™์—ฌ์„œ ๋’ค์—์„œ 2์ž๋ฆฌ๋งŒ ์ž˜๋ผ์„œ ๊ฐ’์„ ๋ณ€ํ™˜ํ•ด์•ผ ํ•œ๋‹ค.

 

์‹œ๊ฐ„ ํฌ๋งท ๋ณ€๊ฒฝํ•˜๊ธฐ (HH:MM:SS)

var today = new Date();   

var hours = ('0' + today.getHours()).slice(-2); 
var minutes = ('0' + today.getMinutes()).slice(-2);
var seconds = ('0' + today.getSeconds()).slice(-2); 

var timeString = hours + ':' + minutes  + ':' + seconds;

console.log(timeString);
// ๊ฒฐ๊ณผ : 15:47:29

 

// ๊ฒฐ๊ณผ : 15:47:29

 

์‹œ๊ฐ„ ํฌ๋งท ๋ณ€ํ™˜ ๋˜ํ•œ ๋‚ ์งœ์™€ ๋น„์Šทํ•˜๋ฉฐ, getHours(), getMinutes(), getSeconds() ํ•จ์ˆ˜๋„ ์ˆ˜์น˜ ๊ฐ’์„ ๋ฐ˜ํ™˜ํ•˜๊ธฐ ๋•Œ๋ฌธ์— 2์ž๋ฆฌ๋ฅผ ๋งž์ถ”๊ธฐ ์œ„ํ•ด์„œ๋Š” "0"์„ ๋ถ™์—ฌ์„œ ๋’ค์—์„œ 2์ž๋ฆฌ๋ฅผ ์ž˜๋ผ์ค˜์•ผ ํ•œ๋‹ค.

profile on loading

Loading...