You need to sign in to do that
Don't have an account?

Creating a datetime instance using a specific time zone
Hello,
I need to create records to check the SLA on our daily batch operations. The SLAs times are stored in its own object using a string to indicate HH:MM and a picklist value to specify the timezone for the client. Each day I need to generate the expected SLA record based on the date and the time stored in SLA times object to compare against the actual. Ideally, I should be able to create a datetime instance specifying the relevant time zone. However, the only options avaialble in Apex are GMT or current user locale.
Is there a way to accomplish the same using what's available in Apex?
I could store the time offset from our default time zone (EST) in the SLA object. However, I would need to deal with the periods when Europe and North America switch daylights savings at different dates.
Thanks,
Pedro
You probably want to use the values in User.TimeZoneSidKey like (America/New_York) to represent time zones as they are standard. I found that I could construct a date in GMT and a specific time zone. Compute the difference, then adjust the input date. That's inelegant but it works.
string dateTimeStr = inDateTime.format('yyyy-MM-dd HH:mm:ss', timeZoneStr);
string dateGmtStr = inDateTime.formatGMT('yyyy-MM-dd HH:mm:ss');
Datetime localDateTime = DateTime.valueOf(dateTimeStr);
Datetime baseGMTTime = DateTime.valueOf(dateGMTStr);
Long milliSecDiff = baseGMTTime.getTime() - localDateTime.getTime();
Long minDiff = milliSecDiff / 1000 / 60;
Datetime outDateTime = inDateTime.addMinutes(minDiff.intValue());
All Answers
You probably want to use the values in User.TimeZoneSidKey like (America/New_York) to represent time zones as they are standard. I found that I could construct a date in GMT and a specific time zone. Compute the difference, then adjust the input date. That's inelegant but it works.
string dateTimeStr = inDateTime.format('yyyy-MM-dd HH:mm:ss', timeZoneStr);
string dateGmtStr = inDateTime.formatGMT('yyyy-MM-dd HH:mm:ss');
Datetime localDateTime = DateTime.valueOf(dateTimeStr);
Datetime baseGMTTime = DateTime.valueOf(dateGMTStr);
Long milliSecDiff = baseGMTTime.getTime() - localDateTime.getTime();
Long minDiff = milliSecDiff / 1000 / 60;
Datetime outDateTime = inDateTime.addMinutes(minDiff.intValue());
Ken,
Thanks a lot. I use your sample to compute the difference between GMT and the required time zone for a particular date and then adjust the datetime variable accordingly. Since we are lacking the Apex functionality to directly do this, I'm not sure you could do this in a simpler more elegant way.
Thanks,
Pedro