与nodejs服务器端

时间:2016-06-06 05:03:34

标签: javascript node.js date datetime

我有一个nodejs应用程序,它托管在IST时区服务器中。该应用程序具有从用户接受timezone的配置(太平洋夏令时)。因此,基于用户timezone,我需要向他显示数据。但是,当我为服务器中的特定用户提取timezone以检索服务器中的某些统计数据时,即使提取了正确的timezone,它仍会返回与服务器相关的Date(),而不是根据用户首选timezone。下面是以下代码:

var offset=-8; //(Pacific Daylight Time)
var d = new Date( new Date().getTime() + offset * 3600 * 1000);

上述var d仍会捕获服务器时区,并根据服务器timezone提取数据。 如何在服务器中获取与date的时区偏好相关的client

2 个答案:

答案 0 :(得分:1)

在服务器端代码var d = new Date( new Date().getTime() + offset * 3600 * 1000);中,总是返回服务器时间而不是客户端的时区,因为它在服务器上执行。因此,您可以将客户端的时间作为http请求中的字符串发送,然后将时间字符串转换为实际时间。然后,您将获得客户的时区时间。希望你的问题能够得到解决。

答案 1 :(得分:1)

如果您已在服务器中存储了用户的首选时区偏移量,则可以根据任何系统的当前系统时间为该时区创建日期和时间。

日期内部时间值为UTC,因此对于任何日期,您可以按偏移量调整时间值,然后使用UTC方法以所需格式输出要求值并附加时区。

但是,始终使用UTC并让主机系统根据系统设置生成日期值非常简单。

/* Given a Date, return an ISO 8601 formatted date and time string
** for a particular time zone.
** @param {number} offset - offset in minutes +east, -west
** @param {Date} d - date to use, default is now
** @returns {string} ISO 8601 formatted string for supplied time zone offset
*/
function dateForTimezone(offset, d) {

  // Copy date if supplied or use current
  d = d? new Date(+d) : new Date();

  // Use supplied offset or system
  offset = offset || -d.getTimezoneOffset();
  // Prepare offset values
  var offSign = offset < 0? '-' : '+'; 
  offset = Math.abs(offset);
  var offHours = ('0' + (offset/60 | 0)).slice(-2);
  var offMins  = ('0' + (offset % 60)).slice(-2);

  // Apply offset to d
  d.setUTCMinutes(d.getUTCMinutes() - offset);

  // Return formatted string
  return d.getUTCFullYear() + 
    '-' + ('0' + (d.getUTCMonth()+1)).slice(-2) + 
    '-' + ('0' + d.getUTCDate()).slice(-2) + 
    'T' + ('0' + d.getUTCHours()).slice(-2) + 
    ':' + ('0' + d.getUTCMinutes()).slice(-2) + 
    ':' + ('0' + d.getUTCSeconds()).slice(-2) + 
    '.' + ('000' + d.getUTCMilliseconds()).slice(-3) +
    offSign + offHours + ':' + offMins; 
  
}

document.write('Current date and time in US Pacific Daylight Time (PDT) time zone UTC-07:00 is: <br>' +
                dateForTimezone(-420,new Date()));