如何使用 Bootstrap-datetimepicker 获取 Unix 时间戳

How to get Unix timestamp using Bootstrap-datetimepicker

我正在使用来自 https://eonasdan.github.io/bootstrap-datetimepicker/

的第 3 方日期时间选择器

它工作正常,但是,我想获取 Unix 时间戳格式的值。我怎么做? Unix 没有格式化选项。 https://eonasdan.github.io/bootstrap-datetimepicker/Functions/#format

function getValue() {
    var date = $('#datetimepicker1').data('date');
    alert(date); // shows 05/25/2017 5:43 PM
}


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

Short Answer: since that plugin work together with moment.js you can use the momentjs method unix(), like in the following way:

moment($('#datetimepicker1').data('date')).unix()

更新(我在 Internet Explorer 11 上测试)

$('#datetimepicker1').data('DateTimePicker').date().unix()

eonasdan 日期时间选择器有一个很好的 API,您可以使用它以编程方式与选择器交互。

您可以使用 date() 方法:

Returns the component's model current date, a moment object or null if not set.

由于 date() 的值 return 是一个时刻对象,您可以使用 unix() 获取 Unix 时间戳(自 Unix 纪元以来的秒数)。

这是一个工作示例:

function getValue() {
  var date = $('#datetimepicker1').data("DateTimePicker").date();
  if( date ){
    alert(date.unix());
  }
}

$('#datetimepicker1').datetimepicker();
<link href="//cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/css/bootstrap.css" rel="stylesheet"/>
<link href="//cdnjs.cloudflare.com/ajax/libs/bootstrap-datetimepicker/4.17.47/css/bootstrap-datetimepicker.css" rel="stylesheet"/>

<script src="//cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/js/bootstrap.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/bootstrap-datetimepicker/4.17.47/js/bootstrap-datetimepicker.min.js"></script>

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

<button onclick="getValue()" class="btn btn-primary">Get value</button>

请记住,正如 docs 所说:

Note All functions are accessed via the data attribute e.g. $('#datetimepicker').data("DateTimePicker").FUNCTION()