JavaScript Date setFullYear()方法

下面是一个例子 日期设置整年() 方法

null
  • 例子:

    <script>
    // Here a date has been assigned
    // while creating Date object
    var dateobj =
    new Date( 'October 13, 1996 05:35:32' );
    // New year 1992 is being set in above Date
    // Object with the help of setFullYear() method
    dateobj.setFullYear(1992);
    // New year from above Date Object is
    // being extracted using getFullYear()
    var B = dateobj.getFullYear();
    // Printing new year
    document.write(B);
    </script>

    
    

  • 输出:
    1992

这个 日期setFullYear() 方法用于将年份设置为使用date()构造函数创建的日期对象。

语法:

DateObj.setFullYear(year_Value)

参数: 此方法接受一个参数,如上所述,如下所述:

  • 年份价值: 此参数保存用于在Date()构造函数中设置的年份值。

返回值: 它返回由setFullYear()方法设置的更新年份的新日期。

注: 这个 DateObj 是使用Date()构造函数创建的有效日期对象,我们希望在其中设置年份。

以上方法的更多代码如下:

项目1: 如果在Date()构造函数中,我们没有给出任何年份,那么setFullYear()方法仍然会设置new year,并将其作为参数给出。

<script>
// Here year has not been assigned
// while creating Date object
var dateobj =
new Date( 'October 13, 05:35:32' );
// new year 1992 is being set in above Date
// Object with the help of setFullYear() method
dateobj.setFullYear(1992);
// New year from above Date Object is
// being extracted using getFullYear()
var B = dateobj.getFullYear();
// Printing new year
document.write(B);
</script>


输出:

1992

项目2: 如果Date()构造函数中没有给出任何参数,则setFullYear()方法仍会设置year,但月份和日期将变为当前日期。输出2中的月份是3月,因为月份名称从0开始到11,即1月为0,12月为11,30是当前日期。

<script>
// Here nothing has been assigned
// while creating Date object
var dateobj = new Date();
// new year 2007 is being set in above Date
// Object with the help of setFullYear() method
dateobj.setFullYear(2007);
// Year from above Date Object is
// being extracted using getFullYear()
var B = dateobj.getFullYear();
// Month from above Date Object is
// being extracted using getMonth()
var C = dateobj.getMonth();
// Date from above Date Object is
// being extracted using getDate()
var D = dateobj.getDate();
// Printing new year
document.write(B + "<" <br /> ">" );
// Printing current month
document.write(C + "<" <br /> ">" );
// Printing current date
document.write(D);
</script>


输出:

2007
2
30

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

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