Using Apex, how can I format a Datetime variable the same way it is displayed in SOQL result? It seems that SOQL uses the UTC format.

When I run the following query

SELECT CreatedDate FROM Account

I get the following datetime format:


console query result

| improve this question | | | | |
  • Are you asking how to format a DateTime type into an ISO 8601 format or you have a DateTime in ISO 8601 format (as above returned from SOQL) and you are trying to format it in another manner? Related documentation: Date Formats and Date Literals – Mark Pond Mar 20 '17 at 22:22
  • @MarkPond I am looking to format a datetime to format like 2017-01-10T14:53:55.000+0000 using Apex – benahm Mar 20 '17 at 22:23

Using the example given in the DateTime class and calling the formatGMT(string) method with a formatting string found in the Java SimpleDateFormat examples:

DateTime myDateTime = DateTime.newInstance(1993, 6, 6, 3, 3, 3);
String formatted = myDateTime.formatGMT('yyyy-MM-dd\'T\'HH:mm:ss.SSSZ');

Produces this result:

15:41:47:003 USER_DEBUG [3]|DEBUG|1993-06-06T10:03:03.000+0000
| improve this answer | | | | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.