Computer >> Computer tutorials >  >> Programming >> Javascript

Date.getMonth() function in JavaScript


The Date object is a data type built into the JavaScript language. Date objects are created with the new Date( ) as shown below.

Once a Date object is created, a number of methods allow you to operate on it. Most methods simply allow you to get and set the year, month, day, hour, minute, second, and millisecond fields of the object, using either local time or UTC (universal, or GMT) time.

The getMonth() function of the Date object returns the moth (0 represents January and so on...) of its current date.

Syntax

Its syntax is as follows

dateObj.getMonth();

Example

<html>
<head>
   <title>JavaScript Example</title>
</head>
<body>
   <script type="text/javascript">
      var dateObj = new Date('september 26, 89 12:4:25:96');
      document.write("Month of the year: "+dateObj.getMonth());
   </script>
</body>
</html>

Output

Month of the year: 8

Example

Incase if you haven’t mentioned the month of the year while creating the date object, this function returns 0.

<html>
<head>
   <title>JavaScript Example</title>
</head>
<body>
   <script type="text/javascript">
      var dateObj = new Date('89 12:4:25:96');
      document.write("Month of the year: "+dateObj.getmonth());
   </script>
</body>
</html>

Output

Month of the year: 0

Example

In the same way if you haven’t passed anything while creating the date object, this function returns the Current month of the current year.

<html>
<head>
   <title>JavaScript Example</title>
</head>
<body>
   <script type="text/javascript">
      var dateObj = new Date();
      document.write("Month of the year:+ "dateObj.getMonth());
   </script>
</body>
</html>

Output

Month of the year: 9