Search code examples
javascriptdatetimemomentjseonasdan-datetimepicker

.isAfter return even false


I'm using momentjs with Eonasdan plugin and I'm trying to check if the end date is less than the start date, for doing this I'm using the method isAfter:

var start = moment($('#start-datetime').val());
var end = moment($('#end-datetime').val());
console.log((start).isAfter(end));   

this will return even false, the values are so defined:

  • start: 07/02/2019 19:58
  • end: 31/01/2019 19:58

Solution

  • Try passing a specific format string and locale to moment to make sure the string is parsed correctly:

    moment(..., "DD/MM/YYYY HH:mm", "en");
    

    or

    moment.locale("en");
    ...
    moment(..., "DD/MM/YYYY HH:mm");
    

    Demonstration:

    moment.locale("en");
    $("#test-button").click(function() {
      var start = moment($('#start-datetime').val(), "DD/MM/YYYY HH:mm");
      var end = moment($('#end-datetime').val(), "DD/MM/YYYY HH:mm");
      console.log((start).isAfter(end));
    });
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.23.0/moment.min.js"></script>
    <input id="start-datetime" type="text" value="07/02/2019 19:58">
    <input id="end-datetime" type="text" value="31/01/2019 19:58">
    <button id="test-button">Test</button>