javascript 如何根据用户语言格式化日期和显示月份和日期
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16541409/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to format date and display month and day based on user language
提问by Hari Subramaniam
I am trying to display the date and time in javascript based on users browser language preference. I am receiveing the date in UTC format and by using toLocaleString() i am able to convert it to browser time zone. But i also need to convert the day name and month name to browser language.
我正在尝试根据用户浏览器语言首选项在 javascript 中显示日期和时间。我正在接收 UTC 格式的日期,并且通过使用 toLocaleString() 我能够将其转换为浏览器时区。但我还需要将日期名称和月份名称转换为浏览器语言。
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(美国)6/15/2009 下午 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)
回答by pala?н
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"
回答by Matt Johnson-Pint
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. I don't believe there is currently support for Greek, but since it is open-source you could always add it yourself.
moment.js 主页上有实时示例,显示了所有可用的语言。我不相信目前有对希腊语的支持,但由于它是开源的,您可以随时自行添加。