JavaScript Date getMonth()方法

下面是一个例子 Date getMonth() 方法

null
  • 例子:

javascript

<script type= "text/javascript" >
// Creating a Date Object
var DateObj = new Date( 'October 15, 1996 05:35:32' );
// Month from above Date Object is
// Being extracted using getMonth()
var months = DateObj.getMonth();
// Printing month.
document.write(months);
</script>


  • 输出:
9

这个 日期getMonth() 方法用于从给定的日期对象获取月份(0到11)。 语法:

DateObj.getMonth()

参数: 此函数不接受任何参数。 返回值: 它返回给定日期对象的月份。月份是0到11之间的整数值。零(0)表示一月,1表示二月,依此类推到11表示十二月。 以上方法的更多代码如下: 项目1: 在这里,月份的日期应该在1到31之间,因为任何日期的月份都不能大于31。这就是为什么如果Date对象中的月份大于31,它会返回NaN,即不是数字。

javascript

<script type= "text/javascript" >
// Creating a Date Object
var DateObj = new Date( 'October 33, 1996 05:35:32' );
// Month from above Date Object is being
// Extracted using getMonth()
var months = DateObj.getMonth();
// Printing month.
document.write(months);
</script>


输出:

NaN

项目2: 如果未给出月份,则返回零(0)。

javascript

<script type= "text/javascript" >
// Creating a Date Object
var DateObj = new Date( '1996 05:35:32' );
// Month from above Date Object is being
// Extracted using getMonth()
var months = DateObj.getMonth();
// Printing month.
document.write(months);
</script>


输出:

0

方案3: 如果没有给出任何参数,则返回当前月份。

javascript

<script type= "text/javascript" >
// Creating a Date Object
var DateObj = new Date();
// Month from above Date Object is being
// Extracted using getMonth()
var months = DateObj.getMonth();
// Printing month.
document.write(months);
</script>


输出:

2

支持的浏览器: 支持的浏览器 JavaScript Date getMonth()方法 以下列出了:

  • 谷歌Chrome 1及以上版本
  • 边缘12及以上
  • Firefox 1及以上版本
  • Internet Explorer 4及以上版本
  • 歌剧3及以上
  • Safari 1及以上
© 版权声明
THE END
喜欢就支持一下吧
点赞7 分享