Skip to content Skip to sidebar Skip to footer

Javascript Validate Date&time

Ive got a piece of JS that needs to validate and compare a start date and time against an end date and time. So in other words end date & time cannot be less than start date an

Solution 1:

You could write a function that converts time in 12 hour format to time in 24 hour format, something like:

functionconvertTo24HourFormatIfNeeded(timeString) {
    var is12HourFormat = timeString.indexOf("M") !== -1;
    if (is12HourFormat) {
        var isPm = timeString.indexOf("PM") !== -1;
        var timeStringNoSuffix = timeString.split(" ")[0];
        if (isPm) {
            var hoursAndMinutes = timeStringNoSuffix.split(":");
            var hours = hoursAndMinutes[0];
            var convertedHours = (Number(hours) + 12);
            var minutes = hoursAndMinutes[1];
            return convertedHours + ":" + minutes;
        } else {
            return timeStringNoSuffix;
        }
    } else {
        return timeString;
    }
}

Then use it in your code:

var start = convertTo24HourFormatIfNeeded(document.getElementById("timepicker").value);
var end = convertTo24HourFormatIfNeeded(document.getElementById("timepickerEnd").value);

Solution 2:

If you're not adverse to using external libraries, i found MomentJs to be very handy working with dates, and among other things it allows to parse the date in a user-defined format, so you could build your date string accordingly to user selection of AM/PM or 24-hour format and feed it to moment js.

Post a Comment for "Javascript Validate Date&time"