-3

Hello all I am trying to validate start time and end time using javascript as follows

<input type="text" id="txtStartTime" value="5:00 PM" />
    <input type="text" id="txtEndTime" value="01:23 AM" />
    <input type="button" id="btnCompare" value="Compare" onclick="Compare()" />
    <script type="text/javascript">
        function Compare() {
            var strStartTime = document.getElementById("txtStartTime").value;
            var strEndTime = document.getElementById("txtEndTime").value;

            var startTime = new Date().setHours(GetHours(strStartTime), GetMinutes(strStartTime), 0);
            var endTime = new Date(startTime)
            endTime = endTime.setHours(GetHours(strEndTime), GetMinutes(strEndTime), 0);
            if (startTime > endTime) {
                alert("Start Time is greater than end time");
            }
            if (startTime == endTime) {
                alert("Start Time equals end time");
            }
            if (startTime < endTime) {
                alert("Start Time is less than end time");
            }
        }
        function GetHours(d) {
            var h = parseInt(d.split(':')[0]);
            if (d.split(':')[1].split(' ')[1] == "PM") {
                h = h + 24;
            }
            return h;
        }
        function GetMinutes(d) {
            return parseInt(d.split(':')[1].split(' ')[0]);
        }
    </script>

What I need is if I enter in start time as 8:00 AM and end time as 9:00 AM it should return true, if I enter 9:00 AM in start time and end time as 8:00 AM is should return false

Nithya
  • 47
  • 2
  • 14

2 Answers2

0

You can use this function-

function compareDate (a,b) {
        // Compare two dates (could be of any type supported by the convert
        // function above) and returns:
        //  -1 : if a < b
        //   0 : if a = b
        //   1 : if a > b
        // NaN : if a or b is an illegal date
        // NOTE: The code inside isFinite does an assignment (=).
        return (
            isFinite(a.valueOf()) &&
            isFinite(b.valueOf()) ?
            (a>b)-(a<b) :
            NaN
        );
    }

This function only works for Date type. Please find the original link for the solution provided earlier.

Community
  • 1
  • 1
Sudip
  • 647
  • 2
  • 7
  • 28
0

Try the below script, if you are setting the times in hours it will work if you want to validate with minutes too then you need to have a different apporach

function Compare() {
    var startTime= "15:00"; // format hh:mm
    var endTime = "12:00";
    var st = startTime.split(":");
    var et = endTime .split(":");
    var OK = false;

    if (st[0] < et[0]) { OK = false }
    else
    {
        OK = true;
    }
    if (!OK) {
        alert("The end time is less than start time");
    }
}
Developer
  • 8,390
  • 41
  • 129
  • 238