Change the date format to perform the calculation

122932
Tera Expert
Hello how are you?

I need to calculate the difference between two dates, but it's calculating wrong, 
because of the date formatting Example: I need to convert "2021-12-06 08:00:00" to "06-12-2021 08:00:00" to see if it calculates right, this is the script I'm using:

Business Rule:

var gdt1 = new GlideDateTime(current.getDisplayValue('u_data_inicio_lb2'));
var gdt2 = new GlideDateTime(current.getDisplayValue('u_data_termino_lb2'));

var dur = GlideDateTime.subtract(gdt1, gdt2); //the difference between gdt1 and gdt2

current.setValue("u_duracao_lb2",dur);

 

Gracias!
1 ACCEPTED SOLUTION

Hi, 

 

You will need to change the format of date and test it. I tried this script and it returned me 32 days. I have hardcoded the dates. Please change it.

var gdt = new GlideDateTime("01/11/2021 08:00:00");
var myDate = gdt.getDate(); 
var gt = gdt.getTime();

var fd = myDate.getByFormat('dd-MM-yyy') + gt.getByFormat(' HH:mm:ss')
gs.info(fd);  //

var gdts = new GlideDateTime("03/12/2021 08:00:00");
var myDates = gdts.getDate();
var gts = gdts.getTime();

var fds = myDates.getByFormat('dd-MM-yyy') + gts.getByFormat(' HH:mm:ss')
gs.info(fds);

var time1 = new GlideDateTime(fd);
var time2 = new GlideDateTime(fds);
var dur = GlideDateTime.subtract(time1, time2);


gs.info(dur.getDisplayValue());

 

Output showed as -

*** Script: 11-01-2021 08:00:00
*** Script: 12-03-2021 08:00:00
*** Script: 32 Days

View solution in original post

11 REPLIES 11

-O-
Kilo Patron
Kilo Patron

The code should be:

var gdt1 = new GlideDateTime(current.getValue('u_data_inicio_lb2'));
var gdt2 = new GlideDateTime(current.getValue('u_data_termino_lb2'));

var dur = GlideDateTime.subtract(gdt1, gdt2); // the difference between gdt1 and gdt2

current.setValue("u_duracao_lb2", dur);

The display value of a date field is expressed in the current user's time zone and the current user's preferred format. That means the code will work correctly by coincidence if the current user's preferred data/time format is the internal one (yyyy-MM-dd HH:mm:ss) or the US one (MM-dd-yyyy HH:mm:ss) - because those are the two formats the GlideDateTime expects. Actually, according the documentation only the internal format is recognized, but in practice it seems the 2nd one is also recognized. However, most important, no matter the format, it has to be in UTC. That is why one has to use

current.getValue('<date/time field>')

and not

current.getDisplayValue('<date/time field>')

-O-
Kilo Patron
Kilo Patron

Forgot to specify, that getValue returns the value in a date/time field in the system TZ (usually UTC).