var now = new Date(); // 현재 날짜와 시간(시,분,초) 값으로 초기화된 객체 생성


var startDay = new Date(2017,2,1); // 학기 시작일. 2017년 3월 1일(2는 3월을 뜻함)

월(month) 값이 0부터 시작하며 0은 1월, 11은 12월을 뜻한다


* Date 객체 생성 방법

new Date() // 현재 날짜와 시간 값으로 초기화된 객체 생성

new Date(y,m,d) // 각각 차례대로 년,월(0~11),일(1~31)을 나타내며, 이 시간 정보를 가진 객체 생성

new Date(y,m,d,hour,min,sec) // 각각 차례대로 년,월,일,시,분,초의 값이며, 이 시간 정보를 가진 객체 생성


* Date 객체의 주요 메소드

메소드

설명

getFullyear()

2018과 같이 4자리 연도 리턴(getYear(), setYear()는 폐기 되었음)

getMonth()

0~11 사이의 정수 리턴

getDate()

한 달 내의 날짜 리턴 (1~31)

getDay()

한 주 내 요일을 정수로 리턴, 일요일=0, 월요일=1,토요일=6

getHours()

0~23 사이의 정수 시간 리턴

getMinutes()

0~59 사이의 정수 분 리턴

 

getSeconds()

0~59 사이의 정수 초 리턴

 

getMilliseconds()

0~999 사이의 밀리초 리턴

getTime()

197011000초를 기준으로 현재 시간까지 경과된 밀리초 개수 리턴

setFullYear(year)

year을 년도 값으로 저장(getFullYear() 참조)

setMonth(month)

month(0~11)를 달 값으로 저장

setDate(date)

date(1~31)를 한 달 내의 날짜 값으로 저장

setHours(hour)

hour(0~23)를 시간 값을 저장

setMinutes(minute)

minute(0~59)를 분 값으로 저장

setSeconds(second)

second(0~59)를 초 값으로 저장

setMillisecond(ms)

ms(0~999)를 밀리초 값으로 저장

setTime(t)

밀리초 단위인 t 값으로 시간 저장(getTime() 참조)

toUTCString()

객체에 든 시간 정보를 UTC 문자열로 리턴

toLocaleString()

객체에 든 시간 정보를 로칼 표현의 문자열로 리턴

toLocalTimeString()

객체에 든 시간 정보를 로칼 시간 10:12:32와 같이 표현




예제 7-5. Data 객체 생성 및 활용

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Date 객체로 현재 시간 알아내기</title></head>
<body>
<h3>Date 객체로 현재 시간 알아내기</h3>
<hr>
<script>
var now = new Date(); // 현재 시간 값을 가진 Date 객체 생성
document.write("현재 시간 : " + now.toUTCString()
            + "<br><hr>");
document.write(now.getFullYear() + "년도<br>");
document.write(now.getMonth() + 1 + "월<br>");
document.write(now.getDate() + "일<br>");
document.write(now.getHours() + "시<br>");
document.write(now.getMinutes() + "분<br>");
document.write(now.getSeconds() + "초<br>");
document.write(now.getMilliseconds()
            + "밀리초<br><hr>");
 
var next = new Date(2017715121212); // 7은 8월
document.write("next.toLocaleString() : "
            + next.toLocaleString() + "<br>");
</script>
</body>
</html>
 
cs



예제 7-6. 방문 시간에 따라 변하는 배경색 만들기
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>방문 시간에 따라 변하는 배경색</title></head>
<body>
<h3>페이지 방문 초시간이  짝수이면 violet, 홀수이면 lightskyblue 배경</h3>
<hr>
<script>
var current = new Date(); // 현재 시간 값을 가진 Date 객체 생성
if(current.getSeconds() % 2 == 0)
    document.body.style.backgroundColor = "violet";
else
    document.body.style.backgroundColor = "lightskyblue";
 
document.write("현재 시간 : ");
document.write(current.getHours(), "시,");
document.write(current.getMinutes(), "분,");
document.write(current.getSeconds(), "초<br>");
</script>
</body>
</html>
 
cs








Posted by 너래쟁이
: