当前位置: 动力学知识库 > 问答 > 编程问答 >

javascript - Can't get date.toLocaleString() to change time to locale

问题描述:

I'm trying to output dates in JavaScript. The page is going to be used by folk in multiple timezones and languages to I figured it would be best to use toLocaleString().

I've tried the example from MSDN but it isn't working:

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

document.write(date.toLocaleString('en-US', { hour12: false }));

// → "12/19/2012, 19:00:00"

but instead I get

12/20/2012, 03:00:00

I've tried a few browsers both in Linux and Windows but I'm just getting the same result. Is there something obvious that I'm missing?

网友答案:

The fourth argument to Date.UTC is hours (0 to 23) so in your case it's 03:00:00 if you are located in the "zero" timezone. The MSDN example was probably written by someone sitting in e.g. Seattle.

网友答案:

The toLocaleString method is about formatting, it formats the date to an American English format, it does not care about timezones, nor could it.

If you want to deal with time zones, I definitely recommend using a library, like MomentJS, unfortunately working with time is a pain in JavaScript (and to be fair, in most languages). However, if you want to fiddle with native JS, then take a look at the getTimezoneOffset method.

分享给朋友:
您可能感兴趣的文章:
随机阅读: