Warning: Date.prototype.toLocaleFormat is deprecated - JavaScript 编辑

The JavaScript warning "Date.prototype.toLocaleFormat is deprecated; consider using Intl.DateTimeFormat instead" occurs when the non-standard Date.prototype.toLocaleFormat method is used.

Message

Warning: Date.prototype.toLocaleFormat is deprecated; consider using Intl.DateTimeFormat instead

Error type

Warning. JavaScript execution won't be halted.

What went wrong?

The non-standard Date.prototype.toLocaleFormat method is deprecated and shouldn't be used anymore. It uses a format string in the same format expected by the strftime() function in C. The function is no longer available in Firefox 58+.

Examples

Deprecated syntax

The Date.prototype.toLocaleFormat method is deprecated and will be removed (no cross-browser support, available in Firefox only).

var today = new Date();
var date = today.toLocaleFormat('%A, %e. %B %Y');

console.log(date);
// In German locale
// "Freitag, 10. März 2017"

Alternative standard syntax using the ECMAScript Intl API

The ECMA-402 (ECMAScript Intl API) standard specifies standard objects and methods that enable language sensitive date and time formatting (available in Chrome 24+, Firefox 29+, IE11+, Safari10+).

You can now either use the Date.prototype.toLocaleDateString method if you just want to format one date.

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"

Or, you can make use of the Intl.DateTimeFormat object, which allows you to cache an object with most of the computations done so that formatting is fast. This is useful if you have a loop of dates to format.

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"

Alternative standard syntax using Date methods

The Date object offers several methods to build a custom date string.

(new Date()).toLocaleFormat("%Y%m%d");
// "20170310"

Can be converted to:

let now = new Date();
let date = now.getFullYear() * 10000 +
          (now.getMonth() + 1) * 100 + now.getDate();

console.log(date);
// "20170310"

See also

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据

词条统计

浏览:92 次

字数:5620

最后编辑:7 年前

编辑次数:0 次

更多

友情链接

    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文