如何为jQuery Datepicker设置太平洋时间(PST)时区
jQuery Datepicker 太平洋时区(PST/PDT)适配方案
你当前的日期选择器已实现节假日和工作日判断,但所有日期逻辑基于用户本地时区,要切换为太平洋时间基准,需修改日期获取和日期判断的核心逻辑,具体实现如下:
完整修改后代码
$(document).ready(function() { // 节假日列表(基于太平洋时区日期) var natDays = [ [1, 1, 'New Year'], //2014 [1, 20, 'Martin Luther King'], //2014 [2, 17, 'Washingtons Birthday'], //2014 [5, 26, 'Memorial Day'], //2014 [7, 4, 'Independence Day'], //2014 [9, 1, 'Labour Day'], //2014 [10, 14, 'Columbus Day'], //2013 [11, 11, 'Veterans Day'], //2013 [11, 28, 'Thanks Giving Day'], //2013 [12, 25, 'Christmas'] //2013 ]; // 将任意日期转换为太平洋时区(自动处理PST/PDT夏令时) function getPSTDate(date) { const pstOffset = -8 * 60; // PST时区UTC偏移(分钟) const pdtOffset = -7 * 60; // PDT夏令时UTC偏移(分钟) // 转换为UTC时间戳 const utcTime = date.getTime() + date.getTimezoneOffset() * 60 * 1000; const year = new Date(utcTime).getUTCFullYear(); // 计算当年夏令时起止时间(UTC标准) const dstStart = new Date(Date.UTC(year, 2, 14 - (new Date(Date.UTC(year, 2, 1)).getUTCDay() + 6) % 7, 2)); const dstEnd = new Date(Date.UTC(year, 10, 7 - (new Date(Date.UTC(year, 10, 1)).getUTCDay() + 6) % 7, 2)); const isDst = utcTime >= dstStart.getTime() && utcTime < dstEnd.getTime(); // 返回太平洋时区的Date对象 return new Date(utcTime + (isDst ? pdtOffset : pstOffset) * 60 * 1000); } // 获取当前太平洋时区的日期 function getCurrentPSTDate() { return getPSTDate(new Date()); } // 初始化最小日期:基于太平洋时间,14点后自动延后1天 var dateMin = getCurrentPSTDate(); dateMin.setDate(dateMin.getDate() + (dateMin.getHours() >= 14 ? 1 : 0)); AddBusinessDays(dateMin, 4); function AddBusinessDays(curdate, weekDaysToAdd) { // 所有日期操作基于太平洋时区 while (weekDaysToAdd > 0) { curdate.setDate(curdate.getDate() + 1); if (noWeekendsOrHolidays(curdate)[0]) { weekDaysToAdd--; } } } function noWeekendsOrHolidays(localDate) { // 将用户本地日期转换为太平洋时区日期后判断 const pstDate = getPSTDate(localDate); const isWeekend = pstDate.getDay() === 0 || pstDate.getDay() === 6; if (isWeekend) { return [false, 'weekend']; } return nationalDays(pstDate); } function nationalDays(pstDate) { for (i = 0; i < natDays.length; i++) { // 匹配太平洋时区的月日 if (pstDate.getMonth() === natDays[i][0] - 1 && pstDate.getDate() === natDays[i][1]) { return [false, natDays[i][2] + '_day']; } } return [true, '']; } $('#datepicker').datepicker({ inline: true, beforeShowDay: noWeekendsOrHolidays, showOn: "both", firstDay: 0, dateFormat: "dd/mm/yy", // 修正原代码拼写错误:dateformat → dateFormat changeFirstDay: false, showButtonPanel: true, minDate: dateMin }); });
关键修改说明
- 时区转换核心函数:新增
getPSTDate,自动处理太平洋时区的夏令时切换,确保所有日期逻辑基于PST/PDT而非用户本地时区。 - 最小日期初始化:用
getCurrentPSTDate替换原生new Date(),保证最小日期的计算完全以太平洋时间为基准。 - 日期判断逻辑:修改
noWeekendsOrHolidays,先将日期选择器传入的本地日期转换为太平洋时区日期,再判断是否为周末或节假日。 - 配置项修正:修正原代码中
dateformat的拼写错误(jQuery Datepicker配置项为驼峰命名dateFormat)。
内容的提问来源于stack exchange,提问作者Royal Fleur
相关产品推荐
相关产品推荐

