当前位置: 首页>>编程示例 >>用法及示例精选 >>正文


JavaScript Date.now()用法及代码示例

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

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

Date对象的now()函数返回从1开始的毫秒数st1970 年 1 月。

用法

其语法如下

Date.now();

示例

<html>
<head>
   <title>JavaScript Example</title>
</head>
<body>
   <script type="text/javascript">
      var currentDate = Date.now();
      var birthDate = Date.parse('29 sep 1989 00:4:00 GMT');
      document.write(currentDate);
      document.write(", "+birthDate+", ");
      document.write(currentDate - birthDate);
   </script>
</body>
</html>

输出

1537780591654, 623030640000, 914749951654

示例

您可以使用此函数获取当前日期,但由于它返回 1970 年 1 月 1 日起的毫秒数以获取格式化日期,因此将获得的值传递给 Date 构造函数。

<html>
<head>
   <title>JavaScript Example</title>
</head>
<body>
   <script type="text/javascript">
      var currentDate = Date.now();
      document.write(currentDate);
      document.write("<br>");
      document.write(Date(currentDate).toString());
   </script>
</body>
</html>

输出

1539758885099
Wed Oct 17 2018 12:18:05 GMT+0530 (India Standard Time)

相关用法


注:本文由纯净天空筛选整理自Karthikeya Boyini大神的英文原创作品 Date.now() function in JavaScript。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。