JavaScript:Date之间的toString()和toLocaleString()方法之间的区别 [英] JavaScript: Difference between toString() and toLocaleString() methods of Date

查看:151
本文介绍了JavaScript:Date之间的toString()和toLocaleString()方法之间的区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我无法理解 toString() toLocaleString() Date 对象在JavaScript中。我知道的一件事是,每当 Date 对象需要转换为字符串时, toString()将自动调用。

I am unable to understand the difference between the toString() and toLocaleString() methods of a Date object in JavaScript. One thing I know is that toString() will automatically be called whenever the Date objects needs to be converted to string.

以下代码总是返回相同的结果:

The following code returns identical results always:

​var d = new Date();
document.write( d + "<br />" );
document.write( d.toString() + "<br />" );
document.write( d.toLocaleString() );


输出为:

Tue Aug 14 2012 08:08:54 GMT+0500 (PKT)
Tue Aug 14 2012 08:08:54 GMT+0500 (PKT)
Tue Aug 14 2012 08:08:54 GMT+0500 (PKT)


推荐答案

基本上,它会将Date格式化为如何格式化调用函数的计算机,例如在美国的前几个月,在世界其他地区的大部分时间之前的一天。

Basically, it formats the Date to how it would be formatted on the computer where the function is called, e.g. Month before Day in US, Day before Month in most of the rest of the world.

编辑:

由于其他人指出上述参考并不是必需的可靠性,所以从 ECMAScript spec

Because some others pointed out that the above reference isn't necessary reliable, how's this from the ECMAScript spec:


15.9.5.2 Date.prototype.toString()

15.9.5.2 Date.prototype.toString ( )


此函数返回一个String值。 String的内容是实现 - >>依赖,但是旨在以方便,可读的形式表示当前时区中的Date。

This function returns a String value. The contents of the String are implementation->> dependent, but are intended to represent the Date in the current time zone in a convenient, human-readable form.

15.9.5.5 Date.prototype.toLocaleString()

15.9.5.5 Date.prototype.toLocaleString ( )


此函数返回一个String值。 String的内容是实现 - >>依赖,但是旨在以与主机环境当前语言环境的约定相对应的方便,可读的形式表示当前时区中的Date。

This function returns a String value. The contents of the String are implementation->>dependent, but are intended to represent the Date in the current time zone in a convenient, human-readable form that corresponds to the conventions of the host environment‘s current locale.


由于您可以希望假设大多数实现将反映规范,区别在于 toString()只需要可读, toLocaleString()应该以符合用户期望的格式读取,基于他们的区域设置。

Since you can hopefully assume that most implementations will reflect the specification, the difference is that toString() is just required to be readable, toLocaleString() should be readable in a format that the should match the users expectations based on their locale.

这篇关于JavaScript:Date之间的toString()和toLocaleString()方法之间的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆