Date 객체 


  • 시스템의 현재 날짜, 시간을 조회하거나 설정하기 위한 기능을 제공한다.
  • 자바스크립트에서 날짜와 시간을 다루는데 사용되는 객체이다.
  • 이 객체를 생성하기 위해서는 new연산자를 이용하여 만들 수 있다.

 

 

 

let 객체명 = new Date();
let 객체명 = new Date(년, 월-1, 일);

→ Date 객체는 년/월/일/시/분/초에 대한 정보를 내장하고 있다.

 

 

 

 Date 객체의 메소드

객체안에 저장된 정보들을 메서드를 사용하여 리턴받거나 다른값으로 변경할 수 있다.

메서드 설 명
getFullYear() setFullYear(year) 연도
getMonth() setMonth(month) 월(0 ~ 11) 예) 0 : 1월, 1 : 2월, ... , 11 : 12월
getDate() setDate(date) 일. 결과값은 1 ~ 31 중 한 개의 숫자값
getDay() setDay() 요일(0 ~ 6) 예) 0 : 일요일, 1 : 월요일, ... , 6 : 토요일
getHours() setHours(hours) 시(0 ~ 23). 결과값은 0 ~ 23 중 한 개의 숫자값
getMinutes() setMinutes(minutes) 분(0 ~ 59). 결과값은 0 ~ 59 중 한 개의 숫자값
getSeconds() setSeconds(seconds) 초(0 ~ 59). 결과값은 0 ~ 59 중 한 개의 숫자값
getTime()   1970년 1월 1일 이후 현재까지의 시간을 천분의 1초 단위로 리턴한다
getMilliseconds() setMilliseconds(Milliseconds) 밀리초를 설정한다

 

 

 

 Date 객체 예시 1

<head>
<script type="text/javascript">
    
	// Date객체 생성
	let mydate=new Date();
	
	// 년,월,일,시간,분,초를 리턴받기
	let yy=mydate.getFullYear();
	let mm=mydate.getMonth()+1;
	// mydate.setDate(1);
	let dd=mydate.getDate();
	
	// 요일의 이름을 저장하고 있는 배열의 생성
	let days=["일","월","화","수","목","금","토"];
    
	// 0~6(=일~토)의 값이 리턴됨
	let i=mydate.getDay();
	let day=days[i];
	
	let hh=mydate.getHours();
	let mi=mydate.getMinutes();
	let ss=mydate.getSeconds();
	
	let result="오늘은"+yy+"년"+mm+"월"+dd+"일"+day+"요일 입니다<br/>";
	result+="현재시간은"+hh+"시"+mi+"분"+ss+"초 입니다."
	document.write("<h1>현재 날짜와 시간 출력</h1>");
	document.write("<h3>"+result+"</h3>");
	
	document.write("<h1>toXXXString() 메서드 예제</h1>");
	// toLocaleDateString() 함수는 "년/월/일"를 문자열로 반환하는 함수
	document.write("<h3>"+mydate.toLocaleDateString()+"</h3>");
	// toLocaleTimeString() 함수는 "오전/오후 시:분:초"를 문자열로 반환하는 함수
	document.write("<h3>"+mydate.toLocaleTimeString()+"</h3>");
	// toLocaleString() 함수는 "년/월/일 오전/오후 시:분:초"를 문자열로 반환하는 함수
	document.write("<h3>"+mydate.toLocaleString()+"</h3>");
	
	function startTime() {
		let now=new Date();
		let result=now.toLocaleString();
		document.getElementById("timeArea").innerHTML=result;
		window.setTimeout("startTime()",1000);	//setTimeout("호출함수", 1/1000)
		//1초 간격으로 값을 출력합니다.
	}
		
</script>
				
		
</head>
<body onload="startTime()">
		<h1>1초 간격으로 시간 출력</h1>
		<h3 id="timeArea"></h3>
</body>

 

 Date 객체 예시 2

// 1초 간격으로 시계 동작 / 중지
let time_id;				
function start_time() {
	let now = new Date();
	document.getElementById("time").innerHTML=now.toLocaleTimeString();
	time_id=setTimeout("start_time()",1000);
}

function stop_time() {
	clearTimeout(time_id);
}
<button type="button" onclick="start_time()">시계동작</button>
<button type="button" onclick="stop_time()">시계중지</button>
<p id="time"></p>

 

 Date 객체 예시 3

// 3초후에 알람창이 뜸
function showAlert() {
	setTimeout(function () {alert("setTimeout()을 사용하여 표시됩니다")},3000);
}
<p>버튼을 누르면 3초 후에 경고 박스가 화면에 표시됩니다.</p>
<button type="button" onclick="showAlert()">눌러보기</button>

 

 Date 객체 예시 4

// 1초 간격으로 텍스트 색상이 자동으로 변경됨 / 중지
function startTextColor() {
	let element=document.getElementById("target")
	element.style.color=(element.style.color=="red") ? "blue":"red";
	element.style.backgroundColor=(element.style.backgroundColor=="green") ? "yellow":"green";
}		

let id;		
function changeColor() {
	id=setInterval(startTextColor,1000)
}

function stopTextColor() {
	clearInterval(id);
}
<div id="target">
	<p>This is a Text.</p>
</div>
<button type="button" onclick="changeColor()">시작</button>
<button type="button" onclick="stopTextColor()">중지</button>

'box > javascript+' 카테고리의 다른 글

Javascript 내장 객체 - location  (0) 2022.06.30
Javascript 내장 객체 - window  (0) 2022.06.30
Javascript 내장 객체 - Math  (0) 2022.06.30
Javascript 내장 객체 - Array  (0) 2022.06.30
Javascript 내장 객체 - String  (0) 2022.06.30