JavaScript

[Date] JS - getMonth() 메서드 - 월얻기 (= 달얻기 = 달월얻기 = getMonth메서드 = 겟먼스메서드) ※ 홀수달/짝수달 조건문

목차

  1. getMonth() 예제 - 월 얻기
  2. getMonth() 정의
  3. getMonth() 구문
  4. getMonth() 예제 - (홀수달/짝수달) 조건문

 

getMonth() 예제 - 월 얻기

[월을 숫자로 얻기]

 

<button onclick="homzzang()">클릭</button>


<p id="demo"></p>


<script>

function homzzang() {

  const d = new Date();

  let month = d.getMonth();

  document.getElementById("demo").innerHTML = n;

}

</script>

 

결과보기 (결과값: 6) ※ 6은 7월 의미하며, 코드 실행 시기 따라 값 바뀜.)


[월을 이름으로 얻기]

 

<p id="demo"></p>


<script>

const monthArr = ["January","February","March","April","May","June","July","August","September","October","November","December"];


const d = new Date();

let month = monthArr[d.getMonth()];

document.getElementById("demo").innerHTML = month;

</script>

 

결과보기 (결과값: February) ※ 코드 실행 시기 따라, 결과값 바뀜.

 

getMonth() 정의

 

월(=달)을 숫자(0~11)로 얻기.

※ 주의: 월은 0부터 시작. (예: 1월:0, 2월:1, ... ,12월:11)

 


 

1.

반환값이 0부터 시작하므로 홀수달/짝수달 구할 때 주의해야 함.

(즉, 반환값을 2로 나눠 나머지가 0이면 홀수달, 1이면 짝수달.)

 

2. cf. 

 

3.

모든 브라우저 지원.

 

 

getMonth() 구문

 

Date.getMonth()

 


[매개변수]

 

없음.

 


[반환값]

 

월을 숫자 (0 ~ 11)로 반환. (예: 1월:0, 2월:1, ..., 12월:11)

 

 

getMonth() 예제 - (홀수달/짝수달) 다른 코드 실행

[방법1] - 날짜 객체와 월을 분리해 표현

 

<script>

const d= new Date();

let month = d.getMonth();

if (month%2) { // 달(0~11)을 2로 나눈 나머지 있으면 짝수달

  // 짝수달 실행 코드

} else {

  // 홀수달 실행 코드

}

</script>

 


[방법2] - 날짜 객체와 월을 한 줄로 표현

 

<script>

let month = new Date().getMonth();

if(month % 2 == 0){ // 달(0~11)을 2로 나눈 나머지 없으면 홀수달

    //홀수달 실행 코드

}else{

    //짝수달 실행 코드

}

</script>

 



분류 제목
Statement JS - 구문 (Statements)
Statement JS - break 구문 ★ (= break문 = 브레이크문)
Statement JS - continue 구문 ★ (= continue문 = 컨티뉴문)
Statement JS - debugger 구문 (= debugger문 = 디버거문)
Statement JS - do ... while 구문 (= 두와일구문 = 두와일문 = 두와일반복문)
Statement JS - for 구문 (= for문 = 포구문 = 포문 = 포반복문)
Statement JS - for...in 구문 (= 포인구문 = 포인문 = 포인반복문)
Statement JS - function 구문 (= 함수구문)
Statement JS - if ... else if ... else ... 구문 (= if문 = 이프문 = 이프조건문)
Statement JS - return 구문 ★★ (= return문 = return구문 = 리턴문 = 반환문 = 리턴구문)…
Statement JS - switch 조건문 ★ (= switch문 = 스위치문)
Statement JS - throw 구문 (= 쓰로우문 = 쓰로우구문)
Statement JS - try ... catch ... finally 구문 (= 트라이캐치파이널구문)
Statement JS - var 구문 (= 변수정의)
Statement JS - while 구문 (= 와일문 = 와일반복문)
12/89
목록
 홈  PC버전 로그인 일본어
그누앞단언어
그누뒷단언어
그외코딩언어
그누보드
제작의뢰
Q&A
커뮤니티
웹유틸
회원센터
홈짱닷컴 PC버전 로그인