【问题标题】:User in any time zone enters a date in Pacific Time任何时区的用户输入太平洋时间的日期
【发布时间】:2016-08-03 10:08:21
【问题描述】:

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

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

【问题讨论】:

  • 你的输入格式是什么?它只是一个选择下拉菜单吗?如果是这样,选择选项的价值是什么。
  • 另外,它只是一个小时还是你也可以有分钟、天、月?你选择哪一天的时间?

标签: javascript jquery ruby-on-rails


【解决方案1】:

如果我理解得很好,如果您可以将本地(无论是什么)已有的日期(从时间选择器构建)更改为太平洋时间,您的问题将得到解决。

使用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();    
}

【讨论】:

    【解决方案2】:

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

    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()

    【讨论】:

    • 您将如何处理 PST 与 PDT?有时是 8,有时是 7
    • @james 我调整了我的答案,如果你有任何问题请看一下,让我知道
    猜你喜欢
    • 2012-12-08
    • 2018-09-15
    • 2018-12-16
    • 1970-01-01
    • 2015-01-22
    • 1970-01-01
    • 2017-01-29
    • 2015-12-31
    • 1970-01-01
    相关资源
    最近更新 更多