JavaScript Tutorial/Date/getMonth

Материал из Web эксперт
Перейти к: навигация, поиск

Date.getMonth

The getMonth() method returns the month portion of the Date object expressed as an integer from 0 (January) to 11 (December).



<html>
<head>
<title>Current Month</title>
</head>
<body>
<script language="JavaScript" type="text/javascript">
<!--
var current_date = new Date();
month_value = current_date.getMonth();
document.write("Current Month is " + month_value);
//-->
</script>
</body>
</html>


Date.getMonth() with switch statement

<html>
   <script language="JavaScript">
    <!--
    function getMonthString(num)
    {
      var month;    //Create a local variable to hold the string
      switch(num)
      {
        case 0:
          month="January";
          break;
        case 1:
          month="February";
          break;
        case 2:
          month="March";
          break;
        case 3:
          month="April";
          break;
        case 4:
          month="May";
          break;
        case 5:
          month="June";
          break;
        case 6:
          month="July";
          break;
        case 7:
          month="August";
          break;
        case 8:
          month="September";
          break;
        case 9:
          month="October";
          break;
        case 10:
          month="November";
          break;
        case 11:
          month="December";
          break;
        default:
          month="Invalid month";
      }
      return month;
    }
    theDate = new Date();
    document.write("The month is ",getMonthString(theDate.getMonth()));
    -->
    </script>
    </html>


Translate the Date().getMonth() to month name

<html>
<head>
<title>Combine Date Values</title>
</head>
<body>
<script language="JavaScript" type="text/javascript">
<!--
var months = new Array(12);
months[0] = "January";
months[1] = "February";
months[2] = "March";
months[3] = "April";
months[4] = "May";
months[5] = "June";
months[6] = "July";
months[7] = "August";
months[8] = "September";
months[9] = "October";
months[10] = "November";
months[11] = "December";
var current_date = new Date();
month_value = current_date.getMonth();
day_value = current_date.getDate();
year_value = current_date.getFullYear();
document.write("The current date is " + months[month_value] + " " +
day_value + ", " + year_value);
//-->
</script>
</body>
</html>