Hi, I am using the below lines of code to add a date to a field but it seems the date is getting concatenated with last two digits if Year.
String format = “DD/MM/YYYY”
SimpleDateFormat sdf = new SimpleDateFormat(format)
String date = sdf.format(new Date()+30)
My expected result will be date should added as current date + 30 days but when running the script , it is adding the date as 165/06/2020.
Can you please advise!
DateFormat dateFormat = new SimpleDateFormat(“yyyy/MM/dd HH:mm:ss”);
Date currentDate = new Date();
// convert date to calendar
Calendar c = Calendar.getInstance();
c.setTime(currentDate);
// manipulate date
c.add(Calendar.YEAR, 1);
c.add(Calendar.MONTH, 1);
c.add(Calendar.DATE, 1); //same with c.add(Calendar.DAY_OF_MONTH, 1);
c.add(Calendar.HOUR, 1);
c.add(Calendar.MINUTE, 1);
c.add(Calendar.SECOND, 1);
// convert calendar to date
Date currentDatePlusOne = c.getTime();
The script needs the datetime value of TODAY. I will use java.time.LocalDateclass to get it.
The LocalDate class provides plusDays(int n) and other convenient methods. We can calculate the date of Tomorrow ( today.plusDays(1) ) or Yesterday ( today.minusDays(1) ) just easily.
Datetime value displayed in a web page is formatted in various ways. Often date display is tailored according to Locale. E.g, in Japan, I may see 令和2年5月16日. I need to format the today’s date to cope exactly with the format applied in the web page. I will use java.time.format.DateTimeFormatterto format the instance of java.time.LocalDate into a String.
Okay, I would be interested to know what the error message was–if it was to do with the date’s format or not having a declared variable. I am going to assume it was the date’s format that was incorrect. So, you can start by something like (note the swap in position of day and month):
Copy and paste the following code as a Test Case in KS and run it. You can see how SimpleDateFormat works.
import java.text.SimpleDateFormat
import com.kms.katalon.core.webui.keyword.WebUiBuiltInKeywords as WebUI
def today = new Date()
def other = today + 30
def sdf1 = new SimpleDateFormat("DD/MM/YYYY") // DD means day in year
WebUI.comment("today=${sdf1.format(today)}") // today=145/05/2020
WebUI.comment("other=${sdf1.format(other)}") // other=175/06/2020
def sdf2 = new SimpleDateFormat("dd/MM/yyyy") // dd means day in month
WebUI.comment("today=${sdf2.format(today)}") // today=24/05/2020
WebUI.comment("other=${sdf2.format(other)}") // other=23/06/2020
// See Javadoc of java.text.SimpleDateFormat
// https://docs.oracle.com/javase/7/docs/api/java/text/SimpleDateFormat.html