본문 바로가기

COA Lab's JS

자바스크립트 12 - 내장객체 Date(), Math()

1. 내장객체 Date()는 년월일시분초 의 정보를 가지고 있는 개체이다.

이 날자와 시간정보를 가지고 있는 Date()객체는 문서에서 사용하려면, new 키워드로 생성 한 후, 사용할 수 있다. 

아래 코드는 Date()객체를 생성하여 today 변수에 담아두고,

이 today변수에 담긴 날자와 시간정보를 불러오는 방법이다.

[Tip]

1.  getMonth() :  월 정보는 0~11까지이므로 반환되는 값에 1을 더해줘야, 현재 월 정보를 가져올 수 있다. 

2. getDay() : 요일정보는 0~6까지 일요일부터 토요일이 나오게 된다.

3. getTime() : 1970.1.1 부터 경과한 시간을 밀리초 단위로 반환해 준다 .

4. 참고 :  Math.round() 는 반올림하는 math객체이다.

let today = new Date();
let nowMonth = today.getMonth()+1;//0~11
let nowDate = today.getDate();
let nowDay = today.getDay();//0(일요일)~6(토요일)
let nowHours = today.getHours();
let nowMins = today.getMinutes();
let nowSeconds = today.getSeconds();
let nowTime = today.getTime();//ms <-1/1000초
let passTime = Math.round(nowTime/(1000*60*60*24));

document.write('<h1> 현재 날자/시간 정보</h1>');
document.write('<h3> 현재 월 :  ' + nowMonth + ' 월</h3>');
document.write(`<h3> 현재 일 :    ${nowDate}  일</h3>`);
document.write(`<h3> 1970.1.1 부터 경과한 시간(일)은  ${passTime} 일</h3>`);

document.write('<h1>날짜 바꿔보기</h1>');
today.setMonth(11);//12월
today.setDate(25);
nowMonth = today.getMonth()+1;
nowDate = today.getDate();

document.write(`<h3> 현재 : ${nowMonth} 월  ${nowDate}  일로 변경되었습니다.</h3>`);

 

2. Math()객체는 new키워드 없이 문서에 기본적으로 생성된다. 

[Tip]

1. Math.random() : 0~1 사이의 난수를 발생하는 Math객체의 메서드

2. Math.floor() : 내림하여 정수로 반환하는 Math객체의 메서드

3. Math.ceil() : 올림값을 반환하는 Math객체의 메서드

4. Math.round() : 반올림값을 반환하는 Math객체의 메서드


let today = new Date();
let birth = new Date('2000/10/29');
console.log(today.getTime());   
let interval = today.getTime() - birth.getTime();
intervl = Math.floor(interval/(1000*60*60*24));
document.write(`태어난지 ${interval} 일 경과`);

let ranNum = Math.random();//0~1사이의 난수
let flNum3 = Math.floor(ranNum*3+1); //1~3사이의 난수
let flNum10 = Math.floor(ranNum*10+1); //1~3사이의 난수
console.log(flNum3);
document.write(`0~1사이의 난수는 ${ranNum}입니다. <br>`);
document.write(`1~3사이의 난수는 ${flNum3}입니다. <br>`);
document.write(`1~10사이의 난수는 ${flNum10}입니다. <br>`);