JavaScript

35일차//Javascript//🎈 과제 2 : Date(), prompt로 현재시간 불러오기(날짜, 월, 일, 시간) , 생일까지 남은 일수 구하기

aesup 2021. 3. 3. 16:50
728x90

new Date()는 현재 날짜와 시간을 가지는 객체를 리턴한다.


let today = new Date();   

let year = today.getFullYear(); // 년도
let month = today.getMonth() + 1;  // 월
let date = today.getDate();  // 날짜
let day = today.getDay();  // 요일

document.write(year + '/' + month + '/' + date)
document.write('<br>')
document.write(day);

출력

2021/3/3
3

 

 

<h1>환영합니다</h1>

<form name="f1">

현재시각은 <input type="text" size="10" name="tbox">입니다

</form>



<script type="text/javascript">

function nowTime() {

	var now = new Date();
	var h = now.getHours();
	var m = now.getMinutes();
	var s = now.getSeconds();
	

	if(h < 10){

		h = "0" + h;

	}

	if(m < 10){

		m = "0" + m;

	}

	if(s < 10){

		s = "0" + s;

	}

	document.f1.tbox.value = h + ":" + m + ":" + s;	

}



setInterval('nowTime()', 1000);





</script>

</body>

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<h1>다음 생일까지 남은 일수</h1>

다음 버튼을 클릭하여 생일을 입력하면,<BR>

다음 생일까지 남은 일수를 볼 수 있습니다.<BR>

<br>

<button onclick="count()">생일을 입력</button>



<script type="text/javascript">

function count() {

	

	var birthMonth = prompt("생일월을 1 ~ 12에서 입력하십시오", "");
	//prompt() 함수 
	// 문자열을 입력할때 사용
	// 첫번째는 입력창에 띄우는 메세지
	// 두번째는 입력 부분(안)에 들어가는 메세지

	var birthDate = prompt("생일 날짜를 1 ~ 31에서 입력하십시오", "");

	

//	alert("birthMonth = " + birthMonth);

	

	var now = new Date();		// 현재 날짜

	var birthday =
	new Date(birthMonth+"/"+birthDate+"/"+ now.getFullYear());
	// 생일 날짜

	

	// 생일 날짜 setting

	/* birthday.setMonth(birthMonth - 1);

	birthday.setDate(birthDate); */

	

	var monthSec = birthday.getTime() - now.getTime();
	//일수를 구한다.. getTime()은 초를 리턴한다.
	

	if(monthSec <= 0){	// 올해 생일이 지났을 경우

		//var birthY = birthday.getFullYear();

		birthday.setFullYear(now.getFullYear() + 1);		

		monthSec = birthday.getTime() - now.getTime();

	}

	
	
	var days = monthSec / (24 * 60 * 60 * 1000);
	days = Math.ceil(days);
	

	

	alert("다음 생일까지 " + days + "일 남았습니다");	

}





</script>

</body>
</html>

728x90