1

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?

2
  • The latter output is the format you need for SOQL. Why do you think you are doing anything wrong? Are you having trouble running the query? Commented Jun 6, 2018 at 23:08
  • I understand the format is what I need for SOQL, but the actual day and time returns from the formatting is different by 12 hours. Which means I don't get the expected result from the query. Commented Jun 6, 2018 at 23:16

2 Answers 2

3

You can format the Datetime instance according to GMT:

String correctTimeZoneValue = DateTime.newInstance(myLong).formatGMT(myFormat);
5
  • So I should be doing startDateTime.formatGMT('yyyy-MM-dd\'T\'hh:mm:ss\'Z\'') Commented Jun 6, 2018 at 23:20
  • @Robs Yes. Or you might have to do Datetime.newInstanceGmt(start). Try both. Commented Jun 6, 2018 at 23:21
  • DateTime.newInstanceGmt does not take a Long, and startDateTime.formatGMT('yyyy-MM-dd\'T\'hh:mm:ss\'Z\'') does not return the correct value Commented Jun 6, 2018 at 23:25
  • The values you have provided indicate you have a GMT offset of +11. So using formatGmt should account for that and give you the correct hour. Surely the output is different? What is the new offset? Commented Jun 6, 2018 at 23:29
  • I am not setting an offset. The org has a default timezone of (GMT+01:00) British Summer Time (Europe/London). Commented Jun 6, 2018 at 23:32
1

To get the correct value formatted as a String for the Dynamic SOQL Query, I needed to use this:

startDateTime.formatGMT('yyyy-MM-dd\'T\'HH:mm:ss\'Z\'')

Note:

1) the use of DateTime.formatGMT(format); as Adrian Larson suggested

and

2) the hour needed to be HH rather than hh


Apex code used to debug:

TimeZone tz = UserInfo.getTimeZone();
System.debug('String format: ' + tz.toString());
System.debug('Display name: ' + tz.getDisplayName());
Long start = Long.valueOf('1528329130300');
System.debug('start: ' + start);
DateTime startDateTime = DateTime.newInstance(start);
System.debug('startDateTime: ' + startDateTime);
System.debug('Offset: ' + tz.getOffset(startDateTime));
System.debug('startDateTime: ' + startDateTime.formatGMT('yyyy-MM-dd\'T\'HH:mm:ss\'Z\''));

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.