Convert date into string

Dear Team,

I got following two options to get date:

def mydate = new Date(System.currentTimeMillis())

OR

LocalDateTime now = LocalDateTime.now()

How can I convert them into a string?

such as:

GlobalVariable.name = 'Today’s date is ’ + date

GlobalVariable.name = 'Today’s date is ’ + now

Thanks in advance!

2 Likes

i’ve been using a keyword which uses LocalDateTime, which should be able to do exactly what you need

import java.time.LocalDateTime
import java.time.format.DateTimeFormatter

public static String getDateString(LocalDateTime dateTime, String format="dd/MM/yyyy HH:mm"){
		if(dateTime==null){
			return ""
		}
		DateTimeFormatter formatter = DateTimeFormatter.ofPattern(format);
		String formattedDateTime = dateTime.format(formatter);
		return formattedDateTime
	}
1 Like

Thanks for providing this information: How do you execute it in groovy directly in Katalon?
def mydate = new Date(System.currentTimeMillis())

def string = getDateString()

?

1 Like

you can also call the method directly, if it’s defined as a static method with Functions.getDateString(LocalDateTime.now());
with Functions being the java class that has the function in it
or, for one-time use, you can also use the following

import java.time.LocalDateTime
import java.time.format.DateTimeFormatter
String currenttime=LocalDateTime.now().format(DateTimeFormatter.ofPattern("dd/MM/yyyy HH:mm"))
1 Like