首页
学习
活动
专区
工具
TVP
发布
精选内容/技术社群/优惠产品,尽在小程序
立即前往

Errors: Deprecated toLocaleFormat

信息

代码语言:javascript
复制
Warning: Date.prototype.toLocaleFormat is deprecated; consider using Intl.DateTimeFormat instead

错误类型

警告。JavaScript执行不会停止。

什么地方出了错?

非标准Date.prototype.toLocaleFormat方法已被弃用,不应再使用。它使用与strftime()C中的函数所期望的相同格式的格式字符串。实现将在bug 818634中完全删除。

例子

弃用的语法

Date.prototype.toLocaleFormat方法已被弃用,将被删除(不支持跨浏览器,仅在Firefox中可用)。

代码语言:javascript
复制
var today = new Date(); 
var date = today.toLocaleFormat('%A, %e. %B %Y');

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

使用ECMAScript Intl API的替代标准语法

ECMA-402(ECMAScript Intl API)标准指定了标准对象和方法,使语言敏感的日期和时间格式化(可用于Chrome 24 +,Firefox 29 +,IE11 +,Safari10 +)。

您现在可以使用该Date.prototype.toLocaleDateString方法,如果你只是想格式化一个日期。

代码语言:javascript
复制
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"

或者,您可以使用该Intl.DateTimeFormat对象,该对象允许您在完成大部分计算后缓存对象,以便快速进行格式化。如果你有一个格式化的日期循环,这很有用。

代码语言:javascript
复制
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"

使用Date方法的替代标准语法

Date对象提供了几种构建自定义日期字符串的方法。

代码语言:javascript
复制
(new Date()).toLocaleFormat("%Y%m%d");
// "20170310"

可以转换为:

代码语言:javascript
复制
let now = new Date();
let date = now.getFullYear() * 10000 + 
          (now.getMonth() + 1) * 100 + now.getDate();

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

扫码关注腾讯云开发者

领取腾讯云代金券

http://www.vxiaotou.com