getLocalDate always prints 1 day behind

yundlu316
Kilo Guru

We are developing in a scoped application and running into a lot of confusion when trying to manipulate dates.  One issue we're running into involves getDate() vs. getLocalDate().  We have a table in the back-end that lists out all the pay period start dates as Date field types and we've set our system date format as MM/dd/yyyy.  A pay period start date on that table appears as 05/13/2020.  In our widget server code, we have a simple GlideRecord query:

var startDate = pp.getValue('u_start_date');
var gdt = new GlideDateTime(startDate);
gs.addInfoMessage(gdt.getLocalDate().getDisplayValue());

If the pay period start date is today -- 05/13/2020, the above code would print out 05/12/2020.  If we change getLocalDate to getDate then it prints out the correct date of 05/13/2020.  Can someone explain why this is happening?  We've read that getLocalDate will take into account the system time zone.  We've double checked that and it is set to EST, which is correct.

Thanks!

1 ACCEPTED SOLUTION

funkeke
Kilo Sage

ServiceNow stores all datetimes in UTC. Your date field u_start_date appears to be date-only (meaning no time component). In that case, ServiceNow will store the value as the date at midnight UTC. When you call getLocalDate, ServiceNow will take the internal time and offset it according to the current local timezone. If that timezone is EST, 5 hours will be subtracted from midnight, resulting in a date that appears one day behind. This offset works as expected when the date field includes a time component, but when it is date only, you will see the issue you described. Use getDate instead.

View solution in original post

3 REPLIES 3

funkeke
Kilo Sage

ServiceNow stores all datetimes in UTC. Your date field u_start_date appears to be date-only (meaning no time component). In that case, ServiceNow will store the value as the date at midnight UTC. When you call getLocalDate, ServiceNow will take the internal time and offset it according to the current local timezone. If that timezone is EST, 5 hours will be subtracted from midnight, resulting in a date that appears one day behind. This offset works as expected when the date field includes a time component, but when it is date only, you will see the issue you described. Use getDate instead.

Thank you for that thorough explanation!

Thank you so much.  Can you clarify where "current local timezone" is set?   Where can we find and change the current local timezone?