我正在使用带有 Timeformat 的 BS Datetimepicker。我的目标是获得选定的时间,例如上午 8:30,作为持续时间(长)。
timepicker.data('DateTimePicker').date()
返回一个时刻,但这个时刻还包括日期维度(当前日期),所以如果我然后使用Moment.valueOf()
我不会得到我想要的。
我想到的解决方案是得到(Moment.hours() * 60 + Moment.minutes()) * 60 * 1000
,但我不喜欢它。
有没有更干净的方法来做到这一点?
这里有两种可能的解决方案:
startOf
日期,然后使用计算以毫秒为单位的差异diff
hour
与minute
所选择的时间,然后显示它asMilliseconds
这是一个实时示例:
var timepicker = $("#datetimepicker1").datetimepicker({
format: 'HH:mm'
});
$('#btn1').click(function(){
// Get selected time
var dateSelected = timepicker.data('DateTimePicker').date();
if( !dateSelected ) return;
// Get start of the day
var startDay = dateSelected.clone().startOf('day');
// Get difference (millseconds) from the start of the day and the selected time
var duration = dateSelected.diff(startDay);
console.log(duration);
});
$('#btn2').click(function(){
// Get selected time
var dateSelected = timepicker.data('DateTimePicker').date();
if( !dateSelected ) return;
// Create duration from hours and minutes slected
var duration = moment.duration({
h: dateSelected.hours(),
m: dateSelected.minutes()
});
// Print duration as milliseconds
console.log(duration.asMilliseconds());
});
<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/css/bootstrap.css" rel="stylesheet"/>
<link href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datetimepicker/4.17.37/css/bootstrap-datetimepicker.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.17.1/moment.min.js"></script>
<script src="https://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.37/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 id="btn1" class="btn btn-default" type="button">Get date as duration V.1</button>
<button id="btn2" class="btn btn-default" type="button">Get date as duration V.2</button>
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句