GlideDateTime comparison looks deceptively simple, but the timezone handling will bite you. The before(), after(), and equals() methods convert both dates to the same timezone before comparison, but only if you construct the GlideDateTime objects correctly. Most developers create one from a database field (which is in GMT) and another using new GlideDateTime() (which uses the session timezone), then wonder why their time-based business rules fire at the wrong time.
When to use this
- Checking if a record is overdue in a Business Rule or Scheduled Job
- Determining record age for SLA calculations or data retention policies
- Validating that end dates come after start dates in forms or workflows
- Sorting or filtering operations where you need boolean comparison results
When NOT to use this
- Don't use in Client Scripts β GlideDateTime objects don't exist client-side, use
GlideAjaxto call server-side comparison - Don't use when you need the duration between dates β use
gs.dateDiff()orGlideDurationinstead - Don't use in GlideRecord queries β use
addQuery('due_date', '<', gs.nowDateTime())for better performance - Don't compare dates from different timezones without explicit conversion β the results are unpredictable
Key behaviors and gotchas
- The
equals()method compares down to the millisecond βsys_created_onandsys_updated_onare rarely equal even on new records - Empty datetime fields return
nullwhen converted to GlideDateTime β always check withgs.nil()first - The
getNumericValue()method returns milliseconds since epoch β useful for arithmetic operations and sorting - Database datetime fields are stored in GMT but
getDisplayValue()returns them in the user's timezone - Constructing GlideDateTime with
new GlideDateTime()creates current time in session timezone, not GMT - Comparison methods handle timezone conversion automatically, but both objects must be valid GlideDateTime instances
Never compare a GlideDateTime object directly with a string using standard operators (< > ==). The string conversion is unpredictable and timezone-dependent. Always use the dedicated comparison methods or convert both to numeric values.
Enjoying this? Get one deep-dive per week.
Join 1,000+ ServiceNow pros β scripts, GlideRecord patterns, Flow Designer techniques, and career moves. Free.