問題描述
嗯...好吧,我已經在網上搜索了 2 天,但沒有任何運氣.我已經看到很多關于如何格式化 javascript 日期的答案,例如 new Date().toString("yyyy-MM-dd")... 這將返回類似 2013-04-05 的內容.
Hmmm... Okay so I've been searching the web for 2 days now without any luck. I've seen a lot of answers on how to format a javascript date for example new Date().toString("yyyy-MM-dd")... Which would return something like 2013-04-05.
這絕對不是問題.
我想要的是設置我的操作系統顯示日期的格式,然后檢索該特定格式并將其顯示在瀏覽器中的可能性.
What I want, is the possibility to set the format in which my OS displays dates, then retrieve that specific format and display it in the browser.
例如,假設我將操作系統中的日期格式更改為 MM-yyyy/dd(這是為了爭論,是否可行無關緊要).那么我希望在我的操作系統中看到 04-2013/05,對吧?接下來,我想通過 Javascript 在我的瀏覽器中檢索這種特定格式,以便我可以使用它來格式化整個網頁中的日期.
For example, let's say I changed the format of the date in my OS to MM-yyyy/dd (this is for arguement sakes, whether that would work or not is irrelevant)). Then I'd expect to see 04-2013/05 in my OS, right? Next I want to retrieve this specific format in my browser via Javascript so that I can use this to format my dates throughout my webpage.
如果這是瘋了,無法做到,請告訴我,因為我在搜索中頭疼.另外,如果您說使用 someDateObject.toLocaleDateString() 而沒有確切解釋為什么 .toLocaleDateString 會起作用,我會忽略它,因為我已經嘗試將我的操作系統中的日期格式設置為多個格式,每次我使用 .toLocaleDateString() 時,我都會收到相同的格式:dd/MM/yyyy
If this is lunacy and cannot be done, please tell me, as I've got a headache from searching. Also, if you say use someDateObject.toLocaleDateString() without explaining exactly why .toLocaleDateString would work, I'm going to ignore it, because I've tried setting my date-format in my OS to numerous formats and every single time I use .toLocaleDateString(), I receive the same format: dd/MM/yyyy
推薦答案
.toLocaleDateString 方法的第一個屬性使用的語言環境.
first attribute of .toLocaleDateString method locale(s) used.
您可以通過 navigator.language(在 firefox 或 chrome 中)參數獲取當前語言環境.在 IE 中可以獲取 navigator.browserLanguage 或 navigator.systemLanguage
current locale you can obtain through navigator.language (in firefox or chrome) parameter. in IE you can obtain navigator.browserLanguage or navigator.systemLanguage
在IE以外的瀏覽器中無法通過這種方式獲取系統語言
in browsers other than IE it is impossible to obtain system language this way
之后,您可以調用 new Date.toLocaleString(navigator.language||navigator.browserLanguage),它將根據瀏覽器語言正確格式化
after this you can call new Date.toLocaleString(navigator.language||navigator.browserLanguage) and it will be formated correctly depending on browser language
這篇關于Javascript - 檢索操作系統日期格式的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!