Sunday, July 06, 2014

ServiceNow: gs.dateDiff() returns the wrong results (sorta)

Do you see what is wrong with this code?
var date1 = new GlideDateTime(); 
var date2 = new GlideDateTime(); 
var date3 = new GlideDateTime();
date1.setDisplayValueInternal('2011-08-26 17:12:28'); 
date2.setDisplayValueInternal('2011-08-30 12:33:10'); 
date3.setDisplayValueInternal('2011-08-30 12:43:10'); 
gs.print(gs.dateDiff(date1, date2, true)); 
gs.print(gs.dateDiff(date1, date3, true));
If you run the code, you'll see that gs.dateDiff() returns the same value for the difference between date1/date2 and date1/date3 even though there is a 10 minute difference.  Why is it rounding to the full number of days?  

Well, it turns out that the default string conversion is not what gs.dateDiff() is expecting.  Instead, it is expecting the date/time string in the user's display format.  

(so if your default date / timeformat matches the internal, then you'd actually get the correct results and wonder what I'm complaining about.) 

Instead of just failing, gs.dateDiff() seems to do the math where it can (e.g. the difference in days). This seems a poor choice in that you are giving the impression of valid results when the results are not accurate.

What you need to do to make sure you get the correct results is the following:

gs.print(gs.dateDiff(date1.getDisplayValue(), date2.getDisplayValue(), true));
gs.print(gs.dateDiff(date1.getDisplayValue(), date3.getDisplayValue(), true));
getDisplayValue() converts the internal date format to the one expected in the execution context.





No comments: