반응형

자바스크립트를 이용해 현재 날짜와 시간을 가져오는 방법입니다.

 

  • 현재 날짜와 시간 구하기
var nowDate = new Date();
document.write(nowDate);

 

실행 결과 : Fri Jun 23 2023 15:55:24 GMT+0900 (한국 표준시)

 

 

  • 현재의 년도, 월, 일, 요일 구하기
var nowDate = new Date();

var year = nowDate.getFullYear(); // 년도
var month = nowDate.getMonth() + 1; // 월
var date = nowDate.getDate(); // 일
var day = nowDate.getDay(); // 요일
var dayText = ['일', '월', '화', '수', '목', '금', '토']; 

document.write(year + "." + month + "." + date + " (" + dayText[day] + ")");

 

실행 결과 : 2023.06.23 (금)

 

- getFullYear() : Date 객체의 년도를 가져옴

- getMonth() : Date 객체의 월을 가져옴 1월은 0으로 나오므로 +1을 해주면 됨

- getDate() : Date 객체의 일자를 가져옴

- getDay() : Date 객체의 요일을 가져옴 결과는 0~6 으로 나오는데 0의 경우 일요일, 1의 경우 월요일임

 

 

  • 현재 시간 구하기
var nowDate = new Date();

var hour = nowDate.getHours();
var minute = nowDate.getMinutes();
var second = nowDate.getSeconds();
var millisecond = nowDate.getMilliseconds();

document.write(hour + ":" + minute + ":" + second + " " + millisecond);

 

실행 결과 : 16:5:23 401

 

- getHours() : Date 객체의 시간을 가져옴 (0~23)

- getMinutes() : Date 객체의 분을 가져옴 (0~59)

- getSeconds() : Date 객체의 초를 가져옴 (0~59)

- getMilliseconds() : Date 객체의 밀리초를 가져옴 (0~999)

 

 

반응형

+ Recent posts