Javascript用户使用日期格式设置的区域设置不正确

时间:2014-02-05 21:56:41

标签: javascript date locale date-format

在javascript中,我使用Date.toLocaleDateString来格式化用户区域设置中的日期。虽然理论上它应该有用,但事实并非如此。

我位于英国。我的计算机设置为UK,我的默认语言在系统设置和浏览器内容设置中都设置为en / gb。然而,Firefox始终显示美国格式的日期。是否有一些我不知道的技巧?

格式化的完整代码是:

var timestamp = ...; //some value from ajax call
var dt = new Date(timestamp);
$('#audit-date').text(dt.toLocaleDateString());

在今天的英国,我希望看到05/02/2014,但我看到02/05/2014,这是它的美国版本。

2 个答案:

答案 0 :(得分:3)

快速浏览一下非常棒的MDN文档告诉我你需要一个locale参数,否则结果取决于浏览器。 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toLocaleString

// British English uses day-month-year order
alert(date.toLocaleString("en-GB"));
// → "20/12/2012 03:00:00"

对于更多自定义日期格式,我使用moment.js库。 http://momentjs.com/

答案 1 :(得分:0)

使用此选项传递区域设置。

var locale = window.navigator.userLanguage || window.navigator.language;
alert(date.toLocaleString(locale));