0

我使用BS Datetimepicker與Timeformat。我的目標是將選定時間(例如上午8:30)作爲持續時間(長)。Bootstrap Datetimepicker獲取時間部分只要

timepicker.data('DateTimePicker').date()返回一個矩,但這個矩還包括日期維(當前日期),所以如果我然後使用Moment.valueOf()我沒有得到我想要的。

我想到的解決方案將獲得(Moment.hours() * 60 + Moment.minutes()) * 60 * 1000,但我不喜歡它。

有沒有更乾淨的方法來做到這一點?

+0

您正在使用什麼datetimeoicker?你可以編輯你的問題,顯示你用來初始化datetimepicker的代碼和你想要做什麼? – VincenzoC

+0

重複的http://stackoverflow.com/questions/23454975/how-to-convert-hours-and-minutes-to-minutes-with-moment-js – MGA

+0

我有分開的日期和時間選擇器,我需要得到一個從那兩個長。你的第二個解決方案很好,謝謝。 – irrols

回答

0

這裏有兩個可能的解決方案:

這裏有一個現場示例:

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>