Using the code snippet from my other Q&A answer, you should be able to have:
String data = '2022-06-23T14:00:00+05.30'; // Coming from the API
String zone = 'Asia/Kolkata'; // Coming from the API
Datetime dt = (Datetime) JSON.deserialize('"' + data.substringBefore('+') + '"', Datetime.class);
// Identify the target time zone
TimeZone target = TimeZone.getTimeZone(zone);
// Figure out the offset at this UTC "moment"
Integer offsetAtUTC = target.getOffset(dt);
// Adjust the date/time value to be in the
// target time zone
Datetime targetDatetime = dt.addSeconds(-offsetAtUTC / 1000);
// Now it is in the target time zone, we have
// a new "moment". If the UTC "moment" was
// before a DST transition but the "moment" in
// the target time zone is after that
// transition the calculation will be adrift
Integer offsetAtLocal = target.getOffset(targetDatetime);
if (offsetAtLocal != offsetAtUTC) {
// There's a drift because of a DST
// transition. Correct it
Datetime adjustedDatetime = targetDatetime.addSeconds((offsetAtUTC - offsetAtLocal) / 1000);
Integer offsetAtAdjusted = target.getOffset(adjustedDatetime);
// The correction is conditional; if the corrected time is
// on the same side of the transition as the correction then
// we need to correct, but we must also correct if leaping
// forward regardless
if (offsetAtAdjusted == offsetAtLocal ||
adjustedDatetime > targetDatetime) {
targetDatetime = adjustedDatetime;
}
}
System.debug('Output local: ' + targetDatetime.format('yyyy-MM-dd HH:ss a z', target.getID()));
At the end of this processing, the targetDatetime
represents the input date/time in the target time zone (Asia/Kolkata) though actually is a UTC value (which is how Salesforce stores such values). The debug output is:
Output local: 2022-06-23 14:00 PM IST
Note: the output a given user sees depends on their time zone unless you do explicit formatting to a given time zone like I did here. I did this to demonstrate that the UTC (or as Salesforce call it GMT) value that would be stored does correspond with the input date/time in the given input time zone. Also note that simple System.debug
logging of a Datetime
value actually logs the UTC value.
System.debug
always showsDatetime
values in UTC, not user time zone.