简体   繁体   中英

compare jquery timepicker values

have timepricker set for 24hr as followers:

$(document).ready(function(){
    $('input.timepicker').timepicker({ 
        timeFormat: 'HH:mm', 
        minTime: '04:00',
        interval: 10,
        scrollbar: true,
        dynamic: true
    });
});

I have two field to obtain start and finish times

<input type="text" class="timepicker" name="travelstart" id="travelstart" placeholder="Travel Start" style="width:25%"> 
<input type="text" class="timepicker" name="travelfinish" placeholder="Travel Finish" style="width:25%" readonly/>

need some way of validating that finish time is later than start time. something along the lines of:

var ts = document.getElementById('travelstart')
var fs = document.getElementById('travelfinish')
if (ts.value => fs.value) { return false }

All you need to do is convert the time to a single unit and compare them. Since it's just a 24h timepicker, we can use minutes here:

var ts = document.getElementById('travelstart').value;
var fs = document.getElementById('travelfinish').value;
var startTime, endTime, timeArr;
// split the hours and minutes
timeArr = ts.split(':');
// Hours is in timeArr[0]; minutes in timeArr[1];
startTime = (timeArr[0] * 60) + +timeArr[1];
// do the same for end time:
timeArr = fs.split(':');
endTime = (timeArr[0] * 60) + +timeArr[1];
// Now you can compare them
return startTime >= endTime;

I'm assuming you're using this timepicker jQuery plugin .

First of all if you call just document.getElementById('travelstart').value it returns time in format "04:00 AM" which is probably not what you want so better use:

$('#options-change-event').timepicker().getTime()

to get an actual JavaScript Date object.

Then convert both times to timestamps and then compare it:

var tsDate = $('#options-change-event').timepicker().getTime();
var tsMinutes = 60 * tsDate.getHours() + tsDate.getMinutes();

// ... the same with the seconds timepicker

return tsMinutes > tfMinutes;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM