Harsh_Deep
Giga Sage
Giga Sage

Using GlideDateTime for Time Zone Conversion

ServiceNow’s GlideDateTime class allows developers to manipulate date/time values effectively. Below is an example script demonstrating how to convert the current date/time into a specific time zone, such as IST (Indian Standard Time).

Example Script:

var gdt = new GlideDateTime(); // Gets the current date and time
var gdt1 = new GlideDateTime();

// Sets the target timezone (e.g., IST - Indian Standard Time)
var tz = Packages.java.util.TimeZone.getTimeZone("IST");
gdt1.setTZ(tz);
gdt1.setValue(gdt); // Assigns the original date/time value

// Fetching the converted date/time in string format
var start = gdt1.getDisplayValue();
start = new GlideDateTime(start); // Converts string back to GlideDateTime object

// Output the converted time
gs.info("Converted Date/Time in IST: " + start.getDisplayValue());

Explanation:

  1. Initialize GlideDateTime Objects:

    • gdt captures the current date and time.

    • gdt1 is used to store the converted value.

  2. Set Time Zone:

    • Using Packages.java.util.TimeZone.getTimeZone("IST"), we specify the target time zone.

  3. Convert the Date/Time:

    • gdt1.setTZ(tz); assigns the specified time zone.

    • gdt1.setValue(gdt); updates gdt1 with the original date/time.

  4. Retrieve the Converted Value:

    • gdt1.getDisplayValue(); returns the date/time in the new time zone as a string.

    • The string is then converted back into a GlideDateTime object for further processing.

Converting to Other Time Zones

You can change the getTimeZone("IST") parameter to other time zones like:

  • UTC: getTimeZone("UTC")

  • PST (Pacific Standard Time): getTimeZone("PST")

  • EST (Eastern Standard Time): getTimeZone("EST")

Best Practices

  • Always verify the time zone abbreviation you are using (e.g., some time zones may require full names like "America/New_York").

  • Consider user preferences and system settings when converting times dynamically.

  • Store and process all timestamps in UTC to ensure consistency across global applications.

By leveraging GlideDateTime and TimeZone in ServiceNow, you can seamlessly manage and convert date/time values across different regions, improving the accuracy of your applications.

 

Mark  👍 Helpful if you find my response worthy based on the impact.

 

Regards,

Harsh Deep Singh

4 Comments