Karate framework: how to get timestamp and append to a variable

Viewed 3471

I wish to get the system timestamp and append it to filename

Scenario: fielanem timestamp
* def filename = 'samplefilename.txt'
* def timestamp = java.type("java.time.localdatetime").now()
* print timestamp

I need to get the current timestamp and append it to filename. output : samplefilenameYYYYMMDDHHMMSS.txt

2 Answers

for timestamp you can use

* def getDate =
  """
  function() {
    var SimpleDateFormat = Java.type('java.text.SimpleDateFormat');
    var sdf = new SimpleDateFormat('yyyyMMddHHmmss');
    var date = new java.util.Date();
    return sdf.format(date);
  } 
  """

* def temp = getDate()
* print temp
* def filename = 'samplefilename.txt'
* def finalfilename = filename.split('.')[0]+temp+'.txt'
* print finalfilename

The date-time API of java.util and their formatting API, SimpleDateFormat are outdated and error-prone. I suggest you should stop using them completely and switch to the modern date-time API. Using the modern date-time and formatting API, you can do it as follows:

* def getDate =
  """
  function() {
    var DateTimeFormatter = Java.type('java.time.format.DateTimeFormatter');
    var dtf = DateTimeFormatter.ofPattern('uuuuMMddHHmmss');
    var ldt = java.time.LocalDateTime.now();
    return ldt.format(dtf);
  } 
  """

* def temp = getDate()
* print temp
* def filename = 'samplefilename.txt'
* def finalfilename = filename.split('.')[0]+temp+'.txt'
* print finalfilename

Learn more about the modern date-time API at Trail: Date Time.

Note that LocalDateTime.now() returns date-time in your JVM's timezone i.e. it gives a value equal to LocalDateTime.now(ZoneId.systemDefault()). If you want to get the local date-time with a particular timezone-offset e.g. with timezone-offset of +00:00 hours i.e. ZoneOffset.UTC, you need to use LocalDateTime now(ZoneId zone) e.g. LocalDateTime.now(ZoneOffset.UTC).

Related