Computer >> คอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Javascript

ฟังก์ชัน Date.getMonth() ใน JavaScript


ออบเจ็กต์ Date เป็นประเภทข้อมูลที่สร้างในภาษา JavaScript วัตถุวันที่ถูกสร้างขึ้นด้วย Date( ) ใหม่ดังที่แสดงด้านล่าง

เมื่อสร้างออบเจ็กต์ Date ขึ้นแล้ว จะมีวิธีต่างๆ มากมายที่ช่วยให้คุณดำเนินการกับออบเจ็กต์ดังกล่าว เมธอดส่วนใหญ่อนุญาตให้คุณรับและตั้งค่าฟิลด์ปี เดือน วัน ชั่วโมง นาที วินาที และมิลลิวินาทีของอ็อบเจ็กต์ โดยใช้เวลาท้องถิ่นหรือเวลา UTC (สากลหรือ GMT)

ฟังก์ชัน getMonth() ของออบเจกต์ Date คืนค่ามอด (0 หมายถึงมกราคม และอื่นๆ...) ของวันที่ปัจจุบัน

ไวยากรณ์

มีรูปแบบดังนี้

dateObj.getMonth();

ตัวอย่าง

<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>

ผลลัพธ์

Month of the year: 8

ตัวอย่าง

ในกรณีที่คุณไม่ได้กล่าวถึงเดือนของปีในขณะที่สร้างวัตถุวันที่ ฟังก์ชันนี้จะคืนค่า 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>

ผลลัพธ์

Month of the year: 0

ตัวอย่าง

ในทำนองเดียวกัน หากคุณไม่ได้ส่งผ่านสิ่งใดขณะสร้างวัตถุวันที่ ฟังก์ชันนี้จะคืนค่าเดือนปัจจุบันของปีปัจจุบัน

<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>

ผลลัพธ์

Month of the year: 9