[SalesForce] Apex DateTime formatting for Dynamic SOQL query returning wrong value

I am passing a DateTime as a Long into my Apex controller and storing it in a variable called start, and it has a value of:

1528329130300

When I create a DateTime from the Long

DateTime startDateTime = DateTime.newInstance(start);
System.debug('startDateTime: ' + startDateTime);

I get the expected output:

startDateTime: 2018-06-06 23:52:10

But when I format it for use in a Dymanic SOQL query like this:

startDateTime.format('yyyy-MM-dd\'T\'hh:mm:ss\'Z\'')

I get a different day and time:

2018-06-07T12:52:10Z

I am using this DateTime to query and the difference in value is leaving out records I am expecting to get.

What am I doing wrong with the DateTime formatting?

Best Answer

You can format the Datetime instance according to GMT:

String correctTimeZoneValue = DateTime.newInstance(myLong).formatGMT(myFormat);
Related Topic