Date对象是JavaScript语言中内置的数据类型。日期对象使用新的Date()创建,如下所示。
创建Date对象后,可以使用多种方法对其进行操作。大多数方法仅允许您使用本地时间或UTC(通用或GMT)时间来获取和设置对象的年,月,日,时,分,秒和毫秒字段。
setFullYear()date对象的功能接受代表年份的整数,并用其修改/替换当前年份。
其语法如下
dateObj.setFullYear();
<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("Current date: "+dateObj.toUTCString());
document.write("<br>");
dateObj.setFullYear(99);
document.write("Date after setting the new year: "+dateObj.toUTCString());
</script>
</body>
</html>输出结果
Current date: Tue, 26 Sep 1989 06:34:25 GMT Date after setting the new year: Sat, 26 Sep 2009 06:34:25 GMT
尽管在创建日期对象时未提及月份的年份,但仍可以使用setFullYear()函数进行设置。
<html>
<head>
<title>JavaScript Example</title>
</head>
<body>
<script type="text/javascript">
var dateObj = new Date('23, August');
document.write("<br>");
dateObj.setFullYear(2018)
document.write(dateObj.toDateString());
</script>
</body>
</html>输出结果
Thu Aug 23 2018
同样,尽管在创建日期对象时未将任何值传递给构造函数,但仍可以使用此函数设置年份,并且月份和日期值与当前日期相同。
<html>
<head>
<title>JavaScript Example</title>
</head>
<body>
<script type="text/javascript">
var dateObj = new Date();
document.write("<br>");
dateObj.setFullYear(2018)
document.write(dateObj.toDateString());
</script>
</body>
</html>输出结果
Thu Oct 18 2018