Search code examples
javascriptjavacucumberkarate

Karate | How to subtract two dates in karate


Scenario: Testing date
      Given url 
      When method get
      Then status 200
      And def releaseDate = response.meta.event.releaseDate
      And print "Release Data is: ", releaseDate
      * def today =
        """
        function() {
          var SimpleDateFormat = Java.type('java.text.SimpleDateFormat');
          var sdf = new SimpleDateFormat('MMM dd, yyyy');
          return sdf.format(new java.util.Date());
        }
        """
      * print today()
      * def today = today()
      * eval diff = today- releaseDate
      And print "Difference is: ", diff
      And assert diff >= 14
* def datediff =
        """
        function(first, second) {
        return Math.round((second - first) / (1000 * 60 * 60 * 24));
        }
        """
      * eval diff = datediff(today, releaseDate)

Getting the following

16:16:02.894 [main] INFO com.intuit.karate - [print] Release Data is: Aug 15, 2002 16:16:02.965 [main] INFO com.intuit.karate - [print] Dec 08, 2022 16:16:02.974 [main] INFO com.intuit.karate - [print] Today's date is: Dec 08, 2022 16:16:03.044 [main] INFO com.intuit.karate - [print] Difference is: NaN


Solution

  • Here is a solution that should answer all your questions. There can be improvements, but I leave that as a homework for you.

    * def toDate =
    """
    function(date) {
      var Formatter = Java.type("java.time.format.DateTimeFormatter");
      var LocalDate = Java.type("java.time.LocalDate");  
      var dtf = Formatter.ofPattern("yyyy-MM-dd");
      return LocalDate.parse(date, dtf);
    }
    """
    
    * def dateMinus =
    """
    function(dateString, days) {
        var date = toDate(dateString);
        return date.minusDays(days);
    }
    """
    
    * def formatDate =
    """
    function(date) {
      var Formatter = Java.type("java.time.format.DateTimeFormatter");
      var LocalDate = Java.type("java.time.LocalDate");  
      var dtf = Formatter.ofPattern("yyyy-MM-dd");
      return dtf.format(date);
    }
    """
    
    * def beforeDate = '2022-12-08'
    * def afterDate = dateMinus(beforeDate, 5)
    * def afterDateString = formatDate(afterDate)
    * match afterDateString == '2022-12-03'
    

    If you have more questions please refer to the Java LocalDate API.