I'm using BS Datetimepicker with Timeformat. My goal is to get the selected time, for example 8:30am, as a duration (long).
timepicker.data('DateTimePicker').date()
returns a Moment, but this Moment also includes the Date dimension (current day), so if I then use Moment.valueOf()
I'm not getting what I want.
The solution I have in mind would be getting (Moment.hours() * 60 + Moment.minutes()) * 60 * 1000
, but I don't like it.
Is there a cleaner way to do it?
Here two possible solutions:
startOf
the day and then calculate the difference in millisecond using diff
hour
and minute
of the selected time and then showing it asMilliseconds
Here a live sample:
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>