0

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 and time.

Now the problem. I originally only accepted the time in 24 hour(military) Format. but now let the user choose between 12 hour or 24 hour.

Example 13:00 or 1:00 PM

This piece of code work for 24 hour time format, but not for 12, its 12:00 PM that causes the problem.

So I need to adapt this piece of code to work for either 12 hour or 24 hour, but im not sure how to do this.

function validateStartEndTime() {
        var date = document.getElementById("datepickerStart").value;

        var dateEnd = document.getElementById("datepickerEnd").value;

        if (!isValidDate(date)) {
            alert("Not Valid Date");
            return false;
        }
        var start = document.getElementById("timepicker").value;
        var end = document.getElementById("timepickerEnd").value;

        var stDate = new Date(parse(date +" "+ start));
        var enDate = new Date(parse(dateEnd + " "+ end));
        var compDate = enDate - stDate;
        if (compDate >= 0)
            return true;
        else {
            alert("End time must be greater than Start Time ");
            return false;
        }

    }
D-W
  • 5,201
  • 14
  • 47
  • 74

2 Answers2

1

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

function convertTo24HourFormatIfNeeded(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);
Nikita Tkachenko
  • 2,116
  • 1
  • 16
  • 23
0

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.

Grim
  • 1,608
  • 9
  • 12