JavaScript中的Date.setDate()函数

Date对象是JavaScript语言中内置的数据类型。日期对象使用新的Date()创建,如下所示。

创建Date对象后,可以使用多种方法对其进行操作。大多数方法仅允许您使用本地时间或UTC(通用或GMT)时间来获取和设置对象的年,月,日,时,分,秒和毫秒字段。

setDate()date对象的功能接受代表月份中某天的整数,并用它修改/替换当前日期。

语法

其语法如下

dateObj.setDate(5);

示例

<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.setDate(1);

      document.write("Date after modification: "+dateObj.toUTCString());

   </script>

</body>

</html>

输出结果

Current date: Tue, 26 Sep 1989 06:34:25 GMT

Date after modification: Fri, 01 Sep 1989 06:34:25 GMTMT

示例

尽管在创建日期对象时未提及月份的日期,但仍可以使用setDate()函数进行设置。

<html>

<head>

   <title>JavaScript Example</title>

</head>

<body>

   <script type="text/javascript">

      var dateObj = new Date('August, 1989 00:4:00');

      document.write("<br>");

      dateObj.setDate(5)

      document.write(dateObj.toDateString());

   </script>

</body>

</html>

输出结果

Sat Aug 05 1989

示例

同样,尽管在创建日期对象时未将任何值传递给构造函数,但仍可以使用此函数设置日期,并且月份和年份值与当前日期相同。

<html>

<head>

   <title>JavaScript Example</title>

</head>

<body>

   <script type="text/javascript">

      var dateObj = new Date();

      dateObj.setDate(2);

      document.write(dateObj.toDateString());

   </script>

</body>

</html>

输出结果

Tue Oct 02 2018

示例

如果使用此功能将日期设置为零,则日期将设置为上个月的最后一天。

<html>

<head>

   <title>JavaScript Example</title>

</head>

<body>

   <script type="text/javascript">

      var dateObj = new Date('23, August, 1989 00:4:00');

      document.write("<br>");

      dateObj.setDate(0);

      document.write(dateObj.toDateString());

   </script>

</body>

</html>

输出结果

Mon Jul 31 1989

以上是 JavaScript中的Date.setDate()函数 的全部内容, 来源链接: utcz.com/z/326955.html

回到顶部