We have Apex classes that trigger and process a CSV file with rows of data. One of the columns is a time column and it is set up below. We implemented this Apex class in September/October and it worked as expected.
Once we tested in January (after day light savings – Nov 6), the time was off by 1 hour. So I went into the Apex class and fixed it.
The main line of the coding that I updated before Spring Forward (March 13) was the ("-06:00:'). (line 8)
Now after daylight savings again, my time is off by another hour.
Instead of doing this twice a year, since updating Apex Classes is kind of struggle of mine. Is there code I can add to make this work all year round? For example: If the day is before this day, use (-06:00), if not use (-05:00)
Needing code to adjust for daylight savings twice a year.
// 15 START TIME --> STL_Start_Time__c
reqString = inputvalues[15];
if(reqString != '') {
//system.debug('reqString value from csv: '+reqString);
String dtStartStr = reqString;
List<String> dateVals = dtStartStr.split(' ')[0].split('/');
List<String> timeVals = dtStartStr.split(' ')[1].split(':');
String jsonStartDt = dateVals[2]+'-'+dateVals[0]+'-'+dateVals[1]+'T'+timeVals[0]+':'+timeVals[1]+':'+timeVals[2]+'-06:00';
//system.debug('JSON formatted date: '+jsonStartDt);
Datetime startDt = (Datetime)JSON.deserialize('"'+jsonStartDt+'"',Datetime.class);
//system.debug('converted DT'+startDt);
tempReimReqLine.STL_Start_Time__c = startDt;}
else { tempReimReqLine.STL_Start_Time__c = null;}
Best Answer
I'd like to take @sfdcfox's response and extend it. When you consider Daylight Savings Time, this has two transitions in the year (unless DST is being made permanent, as The Fox says). You can visualize these something like the following (the exact time and DST offset can vary depending on the time zone):
You can see there are some oddities;
The fundamental algorithm that @sfdcfox's answer contains is sound. However, the following extended version addresses getting consistent behaviour in DST transitions.
In this example, I've used dates and times that are around and cover the transition date/times for the selected time zone.
Note that this test code can be pasted as anonymous apex and run yourself:
Importantly this tries to provide a consistent or at least valid UTC that represents the input local time. (My local times are built from separate Date and Time components; these have no time zone. It's only when you turn it into a Datetime that you then have a time zone in play.)
The debug output for the above is:
Note the following: