首先,您必须在服务器上执行此操作,因为客户端计算机不知道正确的时区偏移量(可能是 -8 小时或 -7 小时,具体取决于是否为夏令时)并且客户端时钟可能不是准确设置(或可能故意设置错误)。
因此,如果您要将偏移量发送给客户端,您不妨只发送时间。当你发送区域时,不要只发送 PST,因为这对很多人来说是模棱两可的,发送实际的偏移量(UTC -8 或 -7 视情况而定)。或者以 UTC 格式发送截止时间并让用户计算出来。
例如,要将本地时间转换为其他时区,您可以执行以下操作:
var pstOffset = 480; // Standard time offset
var pdtOffset = 420 // Daylight saving offset
var now = new Date();
// Adjust to PST
now.setMinutes(now.getMinutes() + now.getTimezoneOffset() - pstOffset);
alert(now); // Time in PST
但请注意,日期对象仍处于本地时区,因为您无法更改实际偏移量,只能调整时间以允许它。
要发送截止时间并将其转换为本地时间,最简单的方法是发送 UTC 时间戳并在本地框中进行转换,因此:
var ts = '2012-04-24T08:00:00Z'; // UTC cut-off for standard time on 24/4
var tsd = '2012-04-24T07:00:00Z'; // UTC cut-off for daylight saving time on 24/4
function utcToLocal(s) {
var bits = s.split(/[-T:Z]/g); // Split string into useful bits
var d = new Date();
// Set local date object to UTC supplied time
d.setUTCFullYear(bits[0], bits[1] - 1, bits[2]);
d.setUTCHours(+bits[3], +bits[4], +bits[5]);
return d;
}
alert( 'Your clock says it\'s now ' + (new Date()) +
'\nThe cut-off for shipping is ' + utcToLocal(ts));
并根据服务器时间发送适当的 UTC 时间戳(例如,如果他们错过了 4 月 24 日的发货时间,则向他们发送 4 月 25 日的时间)。
编辑
这是一个完整的解决方案,但请记住我说过不要在客户端上这样做:
/* Get the cut-off of 2pm PST or PDT on current or
* next working day. If d is true (e.g. 1) use PDT,
* otherwise use PST
**/
function setCutoffTime(d) {
var pstOffset = 480; // PST offset in minutes
var psdOffset = 420; // PDT offset in minutes
var now = new Date();
var addDays = 0;
var cutoff;
var days = 'Sun Mon Tue Wed Thu Fri Sat Sun'.split(' ');
var months = 'Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec'.split(' ');
// Utility to add a leading zero
function addZ(n) {
return (n<10?'0':'') + n;
}
// Convert to PST time
now.setMinutes(now.getMinutes() +
now.getTimezoneOffset() - (d? psdOffset : pstOffset));
// If after 2pm, push to tomorrow
if (now.getHours() > 14) now.setHours(now.getHours() + 12);
// If on a weekend, push to Monday
if (now.getDay() == 6) addDays = 2;
if (now.getDay() == 0) addDays = 1;
now.setDate(now.getDate() + addDays);
// Now on working day pre 2pm, so set time to 14:00
now.setHours(14, 0, 0);
// And convert back to local time
now.setMinutes(now.getMinutes() - now.getTimezoneOffset() +
(d? psdOffset : pstOffset));
// Return a formatted string - should be a separate function
return 'Shipping cut-off: ' +
addZ(now.getHours()) + ':' +
addZ(now.getMinutes()) + ' on ' +
days[now.getDay()] + ', ' +
now.getDate() + ' ' +
months[now.getMonth()] +
', ' + now.getFullYear();
}
alert(setCutoffTime()); // Cut-off for PST
alert(setCutoffTime(true)); // Cut-off for PDT