如何从bootstrap-datepicker获取UTC时间戳?

时间:2018-11-29 21:23:20

标签: javascript twitter-bootstrap timestamp utc bootstrap-datepicker

如何获取bootstrap-datepicker返回UTC时间戳,而不是根据用户的时区返回时间戳?

我正在使用bootstrap-datepicker的1.8.0版本

下面是一个示例,该示例显示在选择日期时由bootstrap-datepicker返回的时间戳:

HTML

<div class="container">
  <div class="row">
    <div class="col-sm-6">
      <div class="input-group date">
        <input type="text" class="form-control" id="js-date">
        <div class="input-group-addon">
          <span class="glyphicon glyphicon-th"></span>
        </div>
      </div>
    </div>
  </div>
  <div class="row">
    <span id="timestamp-output"></span>
  </div>
</div>

JavaScript

$(document).ready(function() {
  $('#js-date').datepicker();
});

$('#js-date').datepicker().on('changeDate', function (ev) {
  $('#timestamp-output').text(ev.date.getTime());
});

小提琴示例

bootstrap-datepicker example

输出

运行示例并选择日期11/29/2018时,显示的时间戳为1543478400000,对应于:

  

格林尼治标准时间:2018年11月29日,星期四,8:00:00

我需要的是代替它返回时间戳1543449600000,它对应于:

  

GMT:2018年11月29日,星期四,12:00:00 AM

摘要

bootstrap-datepicker中是否有为此配置的选项?还是将返回的本地时间戳转换为UTC时间戳的可靠方法?

2 个答案:

答案 0 :(得分:1)

您可能想看看Moment.js已更新,我将本地时间转换为UTC时间戳。

$(document).ready(function() {
  $('#js-date').datepicker();
});

$('#js-date').datepicker().on('changeDate', function (ev) {
  
  var datetime = new Date(ev.date.getTime());
  // Convert local timestamp to UTC timestamp
  var local = moment(datetime).valueOf();
  var utc = (moment(datetime).add(-(moment().utcOffset()), 'm'));
  utc = moment.parseZone(utc).utc().valueOf();
  
  $('#timestamp-local').text('Local Timestamp is ' + local);
  $('#timestamp-utc').text('UTC Timestamp is ' + utc);
  
  console.log('UTC Offset is ' + moment().utcOffset());
});
<script src="https://rawgit.com/moment/moment/2.22.2/min/moment.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
  <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.8.0/js/bootstrap-datepicker.js"></script>

<div class="container">
  <div class="row">
    <div class="col-sm-6">
      <div class="input-group date">
        <input type="text" class="form-control" id="js-date">
        <div class="input-group-addon">
          <span class="glyphicon glyphicon-th"></span>
        </div>
      </div>
    </div>
  </div>
  <div class="row">
    <span id="timestamp-local"></span><br/>
    <span id="timestamp-utc"></span>
  </div>
</div>

答案 1 :(得分:0)

每个this文档调用:

  

getUTCDate()

还通过Javascript:

  

var date = new Date(ev.date.getTime()+(60000 * date.getTimezoneOffset()));