[JS] Math 객체 / date 객체

형이·2023년 8월 8일
0

JavaScript

목록 보기
10/20
post-thumbnail

📝 JavaScript

🖥️ 1. Math 객체

2-1. 최대값

Math.max()

<body>
    <script>
        // 두 수 중에서 최대값
        let max = Math.max(100, 123);
        document.write("<h1>최대값 : " + max + "</h1>");
    </script>
</body>

2-2. 최소값

Math.min()

<body>
    <script>
        // 두 수 중에서 최소값
        const min = Math.min(100, 123);
        document.write("<h1>최소값 : " + min + "</h1>");
    </script>
</body>

2-3. 원주율

Math.PI

<body>
    <script>
        // 원주율
        document.write("<h1>원주율 : " + Math.PI + "</h1>");
    </script>
</body>

2-4. 소수점 반올림 / 올림 / 내림

Math.round(), Math.ceil(), Math.floor()

<body>
    <script>
        // 소수점 반올림, 올림, 내림
        let num1 = 3.7146;
        document.write("<h1>소수점 반올림 : " + Math.round(num1) + "</h1>")
        document.write("<h1>소수점 올림 : " + Math.ceil(num1) + "</h1>")
        document.write("<h1>소수점 내림 : " + Math.floor(num1) + "</h1>")
    </script>
</body>

2-5. 난수

Math.random()

<body>
    <script>
        // 난수
        document.write("<h1>난수 : " + Math.random() + "</h1>")
    </script>
</body>

EX) 인증번호 만들기

<body>
    <script>
        // 두 수 사이의 난수를 리턴하는 함수
        function random(n1, n2){
            return parseInt(Math.random() * (n2 - n1 + 1)) + n1;
        }

        // 함수 결과 확인 0 ~ 9 사이의 랜덤값 출력
        let num = random(0, 9);
        document.write("<h1>0 ~ 9 사이의 난수 : " + num + "</h1>");

        // 응용 : 5자리 인증번호
        let auth = "";

        for( let i = 0; i < 5; i++ ){
            auth += random(0,9);
        }
        document.write("<h1>인증번호 : " + auth + "</h1>")   
    </script>
</body>

🖥️ 2. date 객체

2-1. 두 날짜의 차이를 구하기 : TimeStamp값 사용

  • 1970년 1월 1일 자정부터 지금까지의 지난 시각을 초 단위로 바꾼 값이다.
  • getTime() 함수를 통해서 1/1000초 단위의 TimeStamp 형태로 변환하여 리턴해준다.
  • (24시간 60분 60초 * 1000) 나누면 두 객체 사이의 날짜 차이값을 구할 수 있다.
  • 나눈 값은 소수점 이하를 절단해야 한다. (Math.floor) 두 객체 사이의 차가 3.5일로 계산된 경우 이는 3일 5시간을 의미하는데 그렇다고 해서 4일로 판단하지는 않기 때문이다.
EX1)

<body>
    <script>
        let mydate = new Date();
        
        // 년, 월, 일 리턴 받기
        let yy = mydate.getFullYear();
        // 월은 0이 1월, 11이 12월을 의미
        let mm = mydate.getMonth() + 1;
        let dd = mydate.getDate();

        let result = yy + "-" + mm + "-" + dd;
        document.write("<h1>" + result + "</h1>");

        // 요일 : 일요일은 0이고, 토요일은 6이다
        let days = ['일', '월', '화', '수', '목', '금', '토'];
        let i = mydate.getDay();    // 요일의 number 리턴
        let day = days[i];
        document.write("<h1>" + day + "</h1>")

        // 현재 시각을 출력
        let hh = mydate.getHours();
        let mi = mydate.getMinutes();
        let ss = mydate.getSeconds();

        let result2 = hh + ":" + mi + ":" + ss;
        document.write("<h1>" + result2 + "</h1>");
        // 2023-8-9
		// 수
		// 1:29:54
    </script>
</body>

EX2)

<body>
    <script>
        // 임의의 날짜, 시간 설정
        let mydate = new Date();
        mydate.setYear(2023);
        mydate.setMonth(4);
        mydate.setDate(13);
        mydate.setHours(9);
        mydate.setMinutes(30);
        mydate.setSeconds(43);
        let days = ['일', '월', '화', '수', '목', '금', '토'];

        // 년, 월, 일, 시, 분, 초를 리턴받기
        let yy = mydate.getFullYear();
        let mm = mydate.getMonth();
        let dd = mydate.getDate();
        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 + "요일"
        + hh + ":" + mi + ":" + ss;
        document.write(result);
        // 2023-4-13-토요일9:30:43
    </script>
</body>

EX3) 

<body>
    <script>
        // 올해는 220일 지났습니다.
        let theday = new Date(2023, 0, 1);
        let today = new Date();
        let cnt = today.getTime() - theday.getTime();

        let day = Math.floor(cnt/(24 * 60 * 60 * 1000));
        document.write("올해는 " + day + "일 지났습니다.");
    </script>
</body>

0개의 댓글