-2

Trying to write a logic in Karate DSL where, I need a date in yyyy-mm-dd format. If day is Saturday then 2 day should get added to the current date, 1 day if the day Sunday. Here is something that I'm trying but it is not working.

    * def logic =
      """
      function() {
  var date =  function() {
  var SimpleDateFormat = Java.type('java.text.SimpleDateFormat');
  var sdf = new SimpleDateFormat('yyyy-MM-dd');
  return sdf.format(new java.util.Date());
  }
  var SimpleDateFormat = Java.type('java.text.SimpleDateFormat');
  var sdf = new SimpleDateFormat('EEEE');
  var day =  sdf.format(new java.util.Date());
  var c = Java.type('java.util.Calendar');
  if (day== 'Saturday')
  return Calendar.add(date(),2);

  }
  """

1 Answers1

1

The legacy date-time API (java.util date-time types and their formatting API, SimpleDateFormat) is outdated and error-prone. It is recommended to stop using it completely and switch to java.time, the modern date-time API*.

Solution using the modern API:

import java.time.DayOfWeek;
import java.time.LocalDate;
import java.time.ZoneId;
import java.time.format.TextStyle;
import java.util.Locale;

public class Main {
    public static void main(String[] args) {
        // Current date
        // Change the JVM's default ZoneId as applicable e.g. ZoneId.of("Asia/Kolkata")
        LocalDate date = LocalDate.now(ZoneId.systemDefault());

        if (date.getDayOfWeek() == DayOfWeek.SATURDAY)
            date = date.plusDays(2);
        else if (date.getDayOfWeek() == DayOfWeek.SUNDAY)
            date = date.plusDays(1);

        System.out.println(date);

        // Print day name
        System.out.println(date.getDayOfWeek().getDisplayName(TextStyle.FULL, Locale.ENGLISH));
    }
}

Output:

2021-05-10
Monday

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


* For any reason, if you have to stick to Java 6 or Java 7, you can use ThreeTen-Backport which backports most of the java.time functionality to Java 6 & 7. If you are working for an Android project and your Android API level is still not compliant with Java-8, check Java 8+ APIs available through desugaring and How to use ThreeTenABP in Android Project.

Arvind Kumar Avinash
  • 71,965
  • 6
  • 74
  • 110