- Subscribe to RSS Feed
- Mark as New
- Mark as Read
- Bookmark
- Subscribe
- Printer Friendly Page
- Report Inappropriate Content
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:
-
Initialize GlideDateTime Objects:
-
gdt
captures the current date and time. -
gdt1
is used to store the converted value.
-
-
Set Time Zone:
-
Using
Packages.java.util.TimeZone.getTimeZone("IST")
, we specify the target time zone.
-
-
Convert the Date/Time:
-
gdt1.setTZ(tz);
assigns the specified time zone. -
gdt1.setValue(gdt);
updatesgdt1
with the original date/time.
-
-
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,581 Views
You must be a registered user to add a comment. If you've already registered, sign in. Otherwise, register and sign in.