Javascript 获得设备时区

前端时间做 Mobile Website 的时候有个需求是显示的日期要和设备时区一样,基本思路是通过 Javascript 获得设备的时区,写到本地 Cookie,然后再传到日期的格式化标签里。代码如下:


function setCookie(c_name, c_value, c_expiredays) {
var exdate = new Date();
exdate.setDate(exdate.getDate() + c_expiredays);
document.cookie = c_name + “=” + c_value +
((c_expiredays == null) ? “” : “;expires=” + exdate.toGMTString()) +
“;path=/”;
}

//Write current timzone to cookie for date format later.
(function () {
var now = new Date();

var offsetInMinutes = now.getTimezoneOffset();
var timezonePrefix = “GMT”;
if (offsetInMinutes < 0) timezonePrefix += "+"; else timezonePrefix += "-"; offsetInMinutes = Math.abs(offsetInMinutes); var hours = parseInt(offsetInMinutes / 60); if (isNaN(hours)) { hours = 0 } var minutes = parseInt(offsetInMinutes % 60); if (isNaN(minutes)) { minutes = 0 } //alert(hours + ":" +minutes); var h = hours < 10 ? "0" + hours : "" + hours; var m = minutes < 10 ? "0" + minutes : "" + minutes; var timezone = timezonePrefix + h + m; setCookie("timezone", timezone); })(); [/javascript] 在JSP里面获得时区: [html]
[/html]