Apex DateTime.format with Unrecognized Timezone Identifier – Missing Validation Constraint
0 reputation · 31 May 2023, 21:35 UTC
0 reputation · 31 May 2023, 21:35 UTC
When using DateTime.format(String format, String timezoneId) in Apex, the method accepts any string for the timezoneId argument. If the supplied identifier does not correspond to a known IANA time zone, the platform silently replaces it with the organization’s default time zone and returns a formatted string based on that fallback.
The goal is to guarantee that regional date conversions reflect the intended zone, especially during daylight‑saving transitions, without relying on undocumented behavior.
Because the fallback is not documented as an error condition, developers cannot depend on the method to signal a mistyped zone, which creates a validation gap and risks incorrect timestamps in integrations.
Should the platform throw an exception when an unrecognized timezoneId is provided? Should developers be required to validate timezoneId against a known list before calling format? Is there a configuration or setting that can enforce strict timezone validation in Apex?
When you call DateTime.format(String, String) with a second argument that is not a valid IANA time‑zone ID, the platform does not throw an exception. Instead, it silently substitutes the organization’s default time zone and returns the formatted string based on that fallback.
format. A common pattern is to keep a static Set of known IANA zones and check membership:public class TimeZoneHelper {
private static final Set VALID_ZONES = new Set{
'America/New_York', 'Europe/London', 'Asia/Tokyo' // … add all needed zones
};
public static void validate(String zoneId) {
if (!VALID_ZONES.contains(zoneId)) {
throw new IllegalArgumentException('Invalid time zone: ' + zoneId);
}
}
}
// Usage
TimeZoneHelper.validate(myZoneId);
String formatted = myDateTime.format('yyyy-MM-dd HH:mm:ss', myZoneId);
TimeZone.getTimeZone(String) (if available in your org) to attempt to resolve the ID; a null return indicates an invalid zone.System.debug or custom logging component can surface unexpected substitutions early.At this time, Salesforce provides no configuration option—neither org‑wide nor deployment‑specific—to enforce strict validation of the timezoneId argument. The fallback behavior is baked into the runtime.
DateTime.now().format('yyyy-MM-dd HH:mm:ss', 'Invalid/Zone') and assert that the output’s offset matches the org’s default offset.'America/New_York', and verify the offset difference.To fine‑tune your validation strategy, it can help to know the org’s default time zone. If it’s not already documented in your integration spec, you might want to add that detail.
Use comments to ask for clarification. Post a solution as an answer.
No question comments on this page.