Get variable as Date in Task Listener

Hi!
I have a listener attached to the “create” event of the tasks to do some logic. I need to assign the due date to one of the variables created during the process start.
I can get the variable value using this code:

public void notify(DelegateTask delegateTask) {
  DelegateExecution ex = delegateTask.getExecution();
  String due_date = ex.getVariable("due_date").toString();

The problem is that I get a string like Sat Feb 13 00:00:00 CET 2021 and the setDueDate method of the delegate task expects a Date, so I have to convert it:

DateFormat formatter = new SimpleDateFormat("EEE MMM dd hh:mm:ss z yyyy");
Date parsedDate = (Date)formatter.parse(fecha_vencimiento);
                                
delegateTask.setDueDate(parsedDate);

Is there a way to obtain the variable value as a Date object instead of a parsed string?

Thanks!

Hey @felipRR,

I am inclined to say “it depends”.

More specifically, it depends on how the variable “due_date” was set in the process instance and - more importantly - what specific type it has. If it is a variable of type Date, you can actually fetch the variable value from the execution with ex.getVariable("due_date") (which will be a java.util.Date then) and directly set it as the task’s due date.

Please note that you did write ex.getVariable("due_date").toString() in your example which will of course always yield a String, no matter if it is a Date object or not.

Hope that helps.

Best,
Tobias

Hi!

You are right, as the variable is defined as a Date, I could get its value casting the return of the getVariable method, like this:

Date due_date = (Date)ex.getVariable("due_date")

Now I don’t have to mess with text parsing anymore. Thanks!

Glad it works for you :+1: