任何时区的用户都在太平洋时间输入日期

时间:2016-08-02 01:08:12

标签: javascript jquery ruby-on-rails

好吧也许我对此非常密集......但是我想知道我是如何做到这一点的,以便全球任何时区的用户使用时间选择器进入太平洋时间的时间,然后看到它在保存后在太平洋时间(PST或PDT,取决于)打印回来。我们以纽约某人为例。我认为流程应该是这样的:

  1. 在输入字段中,此人选择“1pm”(表示太平洋时间下午1点)
  2. JS在东部时间下午1点读取它,将其转换为UTC Unix时间戳
  3. UTC Unix时间戳已发布到数据库
  4. 在显示结果中,时间戳将转换为太平洋时间。但是你看到现在很明显太平洋时间会读到“上午10点”的问题,因为发布时间戳是东部时间

2 个答案:

答案 0 :(得分:0)

基本上,您可以使用以下功能:

function convertUtcToPacificTime(utcDate) {
    var timezoneOffset = new Date().getTimezoneOffset();

    // set the time back 7 hours for PDT or 8 hours for PST
    // from the current utc date
    utcDate.setTime(utcDate.getTime()-(timezoneOffset/60)*3600*1000);
}

.getTimezoneOffset()以分钟为单位检索当前时区和UTC之间的差异,因此我将其除以60.在PDT中,函数将返回420,而在PST 480中(分别为7和8时,分割时)到60)。

您的HTML选择框可能如下所示:

<select class="time-select">
   <option value="<!-- timestamp for 1 pm UTC -->">1 pm</option>
   <option value="<!-- timestamp for 2 pm UTC -->">2 pm</option>
   ...
</select>

获得用户选择的时间戳后,您可以使用上面的函数进行转换:

$('.time-select').change(function() {
   var timestamp = $(this).val();
   var date = new Date(timestamp);
   if (!isNaN(date)) { // check if date is valid
       convertUtcToPst(date);

       // the 'date' var now contains
       // the PST date of the selected timestamp

       // post the timestamp to the DB  
   } else {
       // handle invalid date scenario
   }
});

此外,要计算UTC时间戳,只需在JS Date对象上调用.getTime()

答案 1 :(得分:0)

如果我理解得很清楚,如果您可以在当地(无论是什么)到太平洋时间的时间(从时间选择器构建)更改时区,那么问题就解决了。

使用momentmoment-timezone,您可以执行以下操作:

function convertLocalToPst(localDate) {
  var pacific = moment().tz('US/Pacific');
  var m = moment(moment(d).utc().format("MM/DD/YYYY HH:mm"));

  m = pacific.isDST() ? m.utcOffset('-0800') : m.utcOffset('-0700');
  return m.toDate();    
}
相关问题