简体   繁体   English

如何根据用户语言格式化日期和显示月份和日期

[英]How to format date and display month and day based on user language

I am trying to display the date and time in javascript based on users browser language preference.我正在尝试根据用户浏览器语言首选项在 javascript 中显示日期和时间。 I am receiveing the date in UTC format and by using toLocaleString() i am able to convert it to browser time zone.我正在接收 UTC 格式的日期,并且通过使用 toLocaleString() 我能够将其转换为浏览器时区。 But i also need to convert the day name and month name to browser language.但我还需要将日期名称和月份名称转换为浏览器语言。

For ex对于前任

6/15/2009 1:45:30 PM -> Monday, June 15, 2009 8:45:30 PM (en-US) 6/15/2009 1:45:30 PM -> den 15 juni 2009 20:45:30 (sv-SE) 6/15/2009 1:45:30 PM -> Δευτέρα, 15 Ιουνίου 2009 8:45:30 μμ (el-GR) 2009 年 6 月 15 日下午 1:45:30 -> 2009 年 6 月 15 日星期一晚上 8:45:30(美国)2009 年 6 月 15 日下午 1:45:30 -> den 2009 年 6 月 15 日 20:45 :30 (sv-SE) 6/15/2009 1:45:30 PM -> Δευτέρα, 15 Ιουνίου 2009 8:45:30 μμ (el-GR)

Using toLocaleString you can do this:使用toLocaleString你可以这样做:

var date = new Date(Date.UTC(2012, 11, 20, 3, 0, 0));

// request a weekday along with a long date
var options = {weekday: "long", year: "numeric", month: "long", day: "numeric"};
alert(date.toLocaleString("de-DE", options));
// → "Donnerstag, 20. Dezember 2012"

// an application may want to use UTC and make that visible
options.timeZone = "UTC";
options.timeZoneName = "short";
alert(date.toLocaleString("en-US", options));
// → "Thursday, December 20, 2012, GMT"

If you want consistent output regardless of browser, moment.js is a good option.如果你想要无论浏览器如何都保持一致的输出,moment.js 是一个不错的选择。

// set the desired language
moment.lang('sv');

// use one of the localized format strings
var s = moment(yourDate).format('LLLL');

There are live examples on the moment.js home page , showing all of the available languages. moment.js 主页上有实时示例,显示了所有可用的语言。 I don't believe there is currently support for Greek, but since it is open-source you could always add it yourself.我不相信目前有对希腊语的支持,但由于它是开源的,您可以随时自行添加。

我想在这里添加(因为我没有添加评论的特权)@palaSH答案的补充,即所有语言特定格式的链接谢谢:)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM