【问题标题】:bootstrap datetimepicker, unable to convert date and time to UTC引导 datetimepicker,无法将日期和时间转换为 UTC
【发布时间】:2017-02-11 14:47:50
【问题描述】:

这个问题之前可能已经问过很多次了,但我似乎找不到任何相关信息,所以想知道你们中的任何人都可以给我一些想法。

我正在使用 bootstrap datetimepicker 创建工具,但遇到以下问题,我的输入日期和时间无法通过 moment.js 转换为 UTC 时间

代码如下:

$(document).ready(function()
{
    $('#select').datetimepicker({
        format: 'ddd, MM-DD hh:mm A'
    });
     $('#select').on('dp.change', function (e) {
        $('#example').text(moment(e.date).format("ddd, MM-DD, h:mm A"));
    });

});

<div class='col-md-5'>
   <div class="form-group">
      <div class='input-group date' id='select'>
         <input type='text' class="form-control" />
            <span class="input-group-addon">
              <span class="glyphicon glyphicon-calendar"></span>
            </span>
      </div>
   </div>
</div>

<span id="example">__________</span>

选择值后,输出与您选择的相同,而不是自动转换为 UTC。任何帮助指出我做错了什么都将不胜感激!

【问题讨论】:

  • 这里的假设是您希望将 从本地时间 转换为 UTC。如果你的意思是别的,请澄清。
  • 嗨@Matt Johnson - 感谢您提供这里的信息。你的回答很有趣,我想知道更多,希望你能提供一些例子。假设我希望选择时间始终是纽约时间,无论用户属于哪个时区,并转换为 UTC。我怎样才能实现目标。我查看了即时文档,但无法更好地了解如何。任何帮助将不胜感激!
  • 您需要安装 moment-timezone,然后将 datepicker 上的 timeZone 选项设置为 'America/New_York'。见this part of the bootstrap-datetimepicker docs

标签: jquery momentjs datetimepicker


【解决方案1】:

使用moment.js,您可以将日期转换为utc,然后将其格式化

$('#example').text(moment(e.date).utc().format("ddd, MM-DD, h:mm A"));

【讨论】:

  • 为您解决了这个问题。之前没有转换。
【解决方案2】:

现在,您正在使用 .format() 显示您选择的日期,并将日期选择器所需的相同值传递给它。

如果你想要UTC格式,不要使用moment().format(),而是使用moment.utc().format()

查看 moment.js 文档here

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-12-30
    • 1970-01-01
    • 2021-12-31
    • 2011-01-06
    • 2021-10-06
    • 1970-01-01
    相关资源
    最近更新 更多