2

I wrote javascript function in Karate scenario and the function takes in current date in argument and gets date, year, month and adds them in a array. But for some unknown reason I get NaN values. Please see below karate steps that I have been using.

    * def dateArr2 = []
    * def dateParse =
        """
            function(myOrderDate)
            {
              dateArr2.add(myOrderDate); // this is for test purpose

              var today = new Date(myOrderDate);
              var dd = today.getDate();     
              var mm = today.getMonth()+1; //January is 0!
              var yyyy = today.getFullYear();
              dateArr2.add(yyyy);
              dateArr2.add(mm);
              dateArr2.add(dd);               
            }
        """ 
   * def ongoingDateTime = "2018-10-19T11:53:39.8795965Z"
   * eval dateParse(ongoingDateTime)     

Note, the similar javascript code works for me if I am executing in js execution environment such as sublime-text.

mruanova
  • 6,351
  • 6
  • 37
  • 55
MKod
  • 803
  • 5
  • 20
  • 33

1 Answers1

2

Just keep it simple and use Java please. There are examples in the doc: https://github.com/intuit/karate#java-interop

If it is too troubling, write JS utility functions.

* def toDate =
    """
    function(s) {
      var SimpleDateFormat = Java.type('java.text.SimpleDateFormat');
      var sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS");
      return sdf.parse(s)           
    }
    """ 
* def raw = "2018-10-19T11:53:39.8795965Z"
* def date = toDate(raw)
* print date.day, date.month, date.year

Just look at the API for java.util.Date and you have all of that now.

Peter Thomas
  • 54,465
  • 21
  • 84
  • 248
  • For some reason I have used double quotes, anyways I have updated code with `var today = new Date(myOrderDate)`. Are you able to replicate the issue I am having. For me it is still the same, `Nan` values are getting returned. – MKod Oct 19 '18 at 13:10
  • 1
    I am using java and that is good for me. Myself and other colleagues decided to use java as little as possible, because we want to keep it simple and easy to work with, at one stage we want our Karate framework to be used by everyone including manual QA's and others, with minimal coding, that said we want to stick one language and that is javascript. – MKod Oct 19 '18 at 13:38
  • 1
    @MKod agreed. just that when it comes to Date-s it gets complex and is not worth it. – Peter Thomas Oct 19 '18 at 13:39