javascript 세번째

Park In Kwon·2022년 11월 30일
0

1. Date 내장 객체

  • Date객체는 웹 브라우저가 설치된 PC의 현재 시각을 얻어온다.

      <script>
           let mydate = new Date();
    
           // 년,월,일 리턴받기
           let yy = mydate.getFullYear();
           // 월은 0이 1월, 11이 12월을 의미한다.
           let mm = mydate.getMonth() + 1;
           let dd = mydate.getDate();
    
           const result = yy + "-" + mm + "-" + dd;
           document.write("<h1>" + result + "</h1>");
       </script>
       
       <script>
           // 일요일 0, 토요일이 6
           let days = ['일', '월', '화', '수', '목', '금', '토'];
    
           let mydate = new Date();
    
           // 0 = 일요일 ~ 6 = 토요일 값이 리턴
           let i = mydate.getDay();
           const day = days[i];
           document.write("<h1>" + day + "</h1>");
       </script>
       
       <script>
           // 현재 시각을 출력하기
           const mydate = new Date();
    
           const hh = mydate.getHours();
           const mi = mydate.getMinutes();
           const ss = mydate.getSeconds();
    
           const result = hh + ":" + mi + ":" + ss;
           document.write("<h1>" + result + "</h1>");
    
       </script>
       
       <script>
           // Date 객체에 임의의 날짜/시간 정하기
           const days = ['일', '월', '화', '수', '목', '금', '토'];
    
           let mydate = new Date();
    
           // Date 객체안에 저장된 시각을 임의의 날짜로 변경하기
           mydate.setYear(2010);
           mydate.setMonth(1); // 0부터 시작하니까 2월
           mydate.setDate(14);
           mydate.setHours(12);
           mydate.setMinutes(16);
           mydate.setSeconds(30);
    
           // 년,월,일,시,분,초를 리턴
           let yy = mydate.getFullYear();
           let mm = mydate.getMonth() + 1;
           let dd = mydate.getDate();
           let i = mydate.getDay();
           let day = days[i];
    
           let hh = mydate.getHours();
           let mi = mydate.getMinutes();
           let ss = mydate.getSeconds();
    
           const result = yy + "-" + mm + "-" + dd + " "
                           + day + "요일" + hh + ":" + mi + ":" + ss;
           document.write("<h1>" + result + "</h1>");
       </script>
    
       <script>
           /*
               두 날짜의 차이를 구하기 - TimeStamp 값의 사용
                   - TimeStamp 1970년 1월 1일 자정부터 지금까지 지난 시각을 
                   초 단위로 바꾼값
                   - javascript에서는 getTime()함수를 통해서 Date객체가
                   담고있는 기각을 1/1000초 단위의 TimeStamp형태로 변환하여 
                   리턴해 준다.
                   - (24시간 * 60분 * 60초 * 1000)으로 나누면 날짜 차이값을
                   구할 수 있다.
           */
           // 날짜 객체
           let theday = new Date(2022, 0, 1);
           let today = new Date();
    
           let cnt = today.getTime() - theday.getTime();
    
           let day = Math.floor(cnt / (24 * 60 * 60 * 1000));
           document.write("<h1>올해는 " + day + "일 지났습니다.</h1>"); 
       </script> 
profile
개발자로 진로 변경을 위해 준비하고 있습니다

0개의 댓글