aboutsummaryrefslogtreecommitdiff
path: root/files/zh-cn/web/javascript/reference/global_objects/date/toisostring/index.html
blob: 83dec2f8b12e72057d3b5fbe03c172bf5d643955 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
---
title: Date.prototype.toISOString()
slug: Web/JavaScript/Reference/Global_Objects/Date/toISOString
translation_of: Web/JavaScript/Reference/Global_Objects/Date/toISOString
---
<div>{{JSRef}}</div>

<p><code><strong>toISOString()</strong></code> 方法返回一个 ISO(<a href="http://en.wikipedia.org/wiki/ISO_8601">ISO 8601 Extended Format</a>)格式的字符串: <strong>YYYY-MM-DDTHH:mm:ss.sssZ</strong>。时区总是UTC(协调世界时),加一个后缀“Z”标识。</p>

<div>{{EmbedInteractiveExample("pages/js/date-toisostring.html")}}</div>



<h2 id="Syntax">语法</h2>

<pre class="syntaxbox"><var>dateObj</var>.toISOString()</pre>

<h2 id="例子">例子</h2>

<pre class="brush: js">var today = new Date("05 October 2011 14:48 UTC");
alert(today.toISOString()); // 返回2011-10-05T14:48:00.000Z
</pre>

<p>上例使用了非标准字符串的解析,该字符串在某些旧的浏览器(如IE)中可能无法被正确解析。</p>

<h2 id="Description">Polyfill</h2>

<p>该方法在ECMA-262第5版中被标准化。对于那些不支持此方法的JS引擎可以通过加上下面的代码实现:</p>

<pre class="brush:js">if ( !Date.prototype.toISOString ) {
  ( function() {

    function pad(number) {
      if ( number &lt; 10 ) {
        return '0' + number;
      }
      return number;
    }

    Date.prototype.toISOString = function() {
      return this.getUTCFullYear() +
        '-' + pad( this.getUTCMonth() + 1 ) +
        '-' + pad( this.getUTCDate() ) +
        'T' + pad( this.getUTCHours() ) +
        ':' + pad( this.getUTCMinutes() ) +
        ':' + pad( this.getUTCSeconds() ) +
        '.' + (this.getUTCMilliseconds() / 1000).toFixed(3).slice(2, 5) +
        'Z';
    };

  }() );
}</pre>

<h2 id="规范">规范</h2>

<table class="standard-table">
 <tbody>
  <tr>
   <th scope="col">规范版本</th>
   <th scope="col">规范状态</th>
   <th scope="col">注解</th>
  </tr>
  <tr>
   <td>{{SpecName('ES5.1', '#sec-15.9.5.43', 'Date.prototype.toISOString')}}<br>
    Implemented in JavaScript 1.8</td>
   <td>{{Spec2('ES5.1')}}</td>
   <td>Initial definition.</td>
  </tr>
  <tr>
   <td>{{SpecName('ES6', '#sec-date.prototype.toisostring', 'Date.prototype.toISOString')}}</td>
   <td>{{Spec2('ES6')}}</td>
   <td> </td>
  </tr>
 </tbody>
</table>

<h2 id="浏览器兼容性">浏览器兼容性</h2>

<p>{{Compat("javascript.builtins.Date.toISOString")}}</p>

<h2 id="See_Also">相关链接</h2>

<ul>
 <li>{{jsxref("Date.prototype.toLocaleDateString()")}}</li>
 <li>{{jsxref("Date.prototype.toTimeString()")}}</li>
 <li>{{jsxref("Date.prototype.toUTCString()")}}</li>
</ul>