我有這個日期對象在JavaScript中。從日期對象獲取瀏覽器的時區和日期
var d = new Date();
上述代碼行將在Chrome瀏覽器上運行。我想提取瀏覽器的日期(例如:2016年12月14日)和時區(例如:GMT + 0800)等信息。
我有這個日期對象在JavaScript中。從日期對象獲取瀏覽器的時區和日期
var d = new Date();
上述代碼行將在Chrome瀏覽器上運行。我想提取瀏覽器的日期(例如:2016年12月14日)和時區(例如:GMT + 0800)等信息。
你可以做這樣的事情:
var now = new Date();
document.write(now.toUTCString() + "<br>")
document.write(now.toTimeString() + "<br>")
其他一些屬性是:
toDateString() Converts the date portion of a Date object into a readable string
toGMTString() Deprecated. Use the toUTCString() method instead
toISOString() Returns the date as a string, using the ISO standard
toJSON() Returns the date as a string, formatted as a JSON date
toLocaleDateString() Returns the date portion of a Date object as a string, using locale conventions
toLocaleTimeString() Returns the time portion of a Date object as a string, using locale conventions
toLocaleString() Converts a Date object to a string, using locale conventions
toString() Converts a Date object to a string
toTimeString() Converts the time portion of a Date object to a string
toUTCString() Converts a Date object to a string, according to universal time
而且你甚至可以用moment.js插件來幫你出這一點。它使所有這些任務變得微不足道。
也得到了時區偏移,使用類似:
getTimezoneOffset();
事情是這樣的:
var d = new Date();
var n = d.getTime();
或者這樣:
if (!Date.now) {
Date.now = function now() {
return new Date().getTime();
};
}
按照MDN documentation,getTimezoneOffset
應該能夠讓你的時區。
var d = new Date();
d.getTimezoneOffset(); // returns offset in minutes
至於格式化日期,moment.js是一個預先存在的庫,使日期和時間格式很多,比它需要痛苦少得多的能與偉大的跨瀏覽器支持。