Last active
November 19, 2022 03:23
-
-
Save atuttle/6e428e6a26d4a27b3c70 to your computer and use it in GitHub Desktop.
Dealing with Time Zones in ColdFusion
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!--- | |
Many thanks to Sean Corfield and Ryan Guill who set me down the correct path of java.util.TimeZone | |
---> | |
<cfscript> | |
writeDump(label="Conversion Examples",var={ | |
"0-local-tz": getSystemTZ() | |
,"1-local-now": now() | |
,"2-utc-now": toUTC(now()) | |
,"3-eastern-now": TZtoTZ( getSystemTZ(), now(), "America/New_York" ) | |
,"4-pacific-now": TZfromTZ( "America/Los_Angeles", now() ) | |
,"5-phoenix-now": TZfromTZ( "America/Phoenix", now() ) | |
}); | |
writeDump(label="Avaialable Time Zones",var=getTZList()); | |
//======================================================= | |
function getSystemTZ(){ | |
return createObject("java", "java.util.TimeZone").getDefault().getId(); | |
} | |
function toUTC( required time, tz = "America/New_York" ){ | |
var timezone = createObject("java", "java.util.TimeZone").getTimezone( tz ); | |
var ms = timezone.getOffset( getTickCount() ); //get this timezone's current offset from UTC | |
var seconds = ms / 1000; | |
return dateAdd( 's', -1 * seconds, time ); | |
} | |
function UTCtoTZ( required time, required string tz ){ | |
var timezone = createObject("java", "java.util.TimeZone").getTimezone( tz ); | |
var ms = timezone.getOffset( getTickCount() ); //get this timezone's current offset from UTC | |
var seconds = ms / 1000; | |
return dateAdd( 's', seconds, time ); | |
} | |
function TZtoTZ( localtz, time, targettz ){ | |
return UTCtoTZ( toUTC(time, localtz), targettz ); | |
} | |
function TZfromTZ( targettz, time, sourcetz = getSystemTZ() ){ | |
return TZtoTZ( sourcetz, time, targettz ); | |
} | |
function getTZList(){ | |
var list = createObject("java", "java.util.TimeZone").getAvailableIDs(); | |
var data = {}; | |
for (tz in list){ | |
var ms = createObject("java", "java.util.TimeZone").getTimezone( tz ).getOffset( getTickCount() ); | |
data[ tz ] = readableOffset( ms ); | |
} | |
return data; | |
} | |
function readableOffset( offset ){ | |
var h = offset / 1000 / 60 / 60; //raw hours (decimal) offset | |
var hh = fix( h ); //int hours | |
var mm = ( hh == h ? ":00" : ":" & abs(round((h-hh)*60)) ); //hours modulo used to determine minutes | |
var rep = ( h >= 0 ? "+" : "" ) & hh & mm; | |
return rep; | |
} | |
</cfscript> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Heads up: This gist evolved into a decent utility library: https://github.com/alumniq/momentcfc