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
88
89
90
|
---
title: 'Warning: Date.prototype.toLocaleFormat is deprecated'
slug: Web/JavaScript/Reference/Errors/Deprecated_toLocaleFormat
tags:
- JavaScript
- 警告
translation_of: Web/JavaScript/Reference/Errors/Deprecated_toLocaleFormat
---
<div>{{jsSidebar("Errors")}}</div>
<h2 id="错误提示">错误提示</h2>
<pre class="syntaxbox">Warning: Date.prototype.toLocaleFormat is deprecated; consider using Intl.DateTimeFormat instead
</pre>
<h2 id="错误类型">错误类型</h2>
<p>警告。JavaScript 引擎不会停止运行。</p>
<h2 id="哪里出错了?">哪里出错了?</h2>
<p>{{jsxref("Date.prototype.toLocaleFormat")}} 是非标准化的方法,已经被废弃,不应该再进行使用。该方法需要传入与 C 语言中的strftime() 方法相似的格式化字符串。该实现将会在 {{bug(818634)}} 中完全移除。</p>
<h2 id="示例">示例</h2>
<h3 id="废止使用的语法">废止使用的语法</h3>
<p>{{jsxref("Date.prototype.toLocaleFormat")}} 方法已经废弃,以后会被移除(只在 Firefox 浏览器中有用到,没有在其他浏览器中使用)。</p>
<pre class="brush: js example-bad">var today = new Date();
var date = today.toLocaleFormat('%A, %e. %B %Y');
console.log(date);
// In German locale
// "Freitag, 10. März 2017"</pre>
<h3 id="备选标准语法之一:使用_ECMAScript_Intl_API">备选标准语法之一:使用 ECMAScript Intl API </h3>
<p>ECMA-402 (ECMAScript Intl API) 标准规定了支持不同语言的日期和时间格式化形式的对象和方法(在 Chrome 24+, Firefox 29+, IE11+, Safari10+ 中可用)。</p>
<p>现在如果只需要格式化一个日期对象的话,那么可以使用 {{jsxref("Date.prototype.toLocaleDateString")}} 方法。</p>
<pre class="brush: js example-good">var today = new Date();
var options = { weekday: 'long', year: 'numeric',
month: 'long', day: 'numeric' };
var date = today.toLocaleDateString('de-DE', options);
console.log(date);
// "Freitag, 10. März 2017"
</pre>
<p>或者,可以使用 {{jsxref("DateTimeFormat", "Intl.DateTimeFormat")}} 对象,该对象允许你将格式化器对象缓存起来,省去很多重复性的计算工作,所以格式化操作会很快。这在需要对一系列的日期对象进行格式化的时候非常有用。</p>
<pre class="brush: js example-good">var options = { weekday: 'long', year: 'numeric',
month: 'long', day: 'numeric' };
var dateFormatter = new Intl.DateTimeFormat('de-DE', options)
var dates = [Date.UTC(2012, 11, 20, 3, 0, 0),
Date.UTC(2014, 04, 12, 8, 0, 0)];
dates.forEach(date => console.log(dateFormatter.format(date)));
// "Donnerstag, 20. Dezember 2012"
// "Montag, 12. Mai 2014"
</pre>
<h3 id="备选标准语法之二:使用_Date_对象的方法">备选标准语法之二:使用 Date 对象的方法</h3>
<p>{{jsxref("Date")}} 对象提供了一系列的方法来生成定制化的格式化字符串。</p>
<pre class="brush: js example-bad">(new Date()).toLocaleFormat("%Y%m%d");
// "20170310"
</pre>
<p>可以转换为:</p>
<pre class="brush: js example-good">let now = new Date();
let date = now.getFullYear() * 10000 +
(now.getMonth() + 1) * 100 + now.getDate();
console.log(date);
// "20170310"</pre>
<h2 id="相关内容">相关内容</h2>
<ul>
<li>{{jsxref("Date.prototype.toLocaleFormat")}}</li>
<li>{{jsxref("Date.prototype.toLocaleDateString")}}</li>
<li>{{jsxref("DateTimeFormat", "Intl.DateTimeFormat")}}</li>
</ul>
|