How to check Javascript End time and Time with parsing date with AM / PM?

This is my script.

$(document).on("click","input[name='to_time[]']",function(){
    var from = $("input[name='from_time[]']").val(); // "11:15 AM"
    var to = $("input[name='to_time[]']").val(); //"10:15 AM"

    if(Date.parse(from) > Date.parse(to)){
      alert("Invalid Date Range");
    }
});

From the date of receipt Datepicker in this format "12:54 PM" Date.parse (from) returns as not a number. NaN How to parse this string into a Javascript object, or is there an alternative way to check the end time and time.

+4
source share
1 answer

You can use Moment.js for this. See below

var from =  "11:15 AM";
var to = "10:15 AM";

if (moment(from, 'hh:mm a') > moment(to, 'hh:mm a')) {
  alert("Invalid Date Range");
} else {
  alert("Valid Date Range");
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.19.4/moment.js"></script>
Run codeHide result

Remember to add a format hh:mm awhen converting a time string to an object.

+2
source

Source: https://habr.com/ru/post/1690837/


All Articles