[SalesForce] Combine Date from one datetime field with Time from another

I have tried all sorts of proposed solutions but can't seem to find one that works. I receive 2 DateTime fields from an api call and need to take the Date part from one and combine it with the Time part from the other in my upsert trigger into a datetime field.

datetime dtime = opp.AccModifiedTime__c; //1899-12-30 15:38:19

datetime ddate = opp.AccModifiedDate__c; //2014-08-13 00:00:00

It also seems to save these as GMT time when coming in via the API, which is not what I want – this is the local correct time and I want it to display as such. It will display the hours as 3:38 AM (I'm in NZ, so it's 12hrs before GMT). I need it to display as a datetime field of

13/08/2014 03:38 PM

Can anyone help me please?

Best Answer

You want to use the Datetime.newInstance method with parameters Date, Time.

Datetime withDate; // e.g. 2014-08-13 00:00:00
Datetime withTime; // e.g. 1899-12-30 15:38:19

Datetime withBoth = Datetime.newInstance(withDate.date(), withTime.time());

If you wanted to preserve GMT (doesn't sound that way) you could use withTime.timeGMT().

Related Topic