Converting Date Field to ISO 8601 Format: A Guide

The output provides three solutions to the problem.
Solution 1 suggests removing the “00” from the end of the date format.
Solution 2 recommends using the “format” method to solve the issue.
Solution 3 proposes returning the date as a string using the locale of the context user, or using a specified format regardless of the user’s locale. Additionally, the code can be checked or the link provided for reference.


Solution:

By formatting to GMT, the timezone offset is consistently 00:00, allowing for the following simplified approach:

Datetime startDate = Datetime.newInstanceGmt(2020, 7, 21, 20, 40, 00);
String startDate2 = startDate.formatGmt('yyyy-MM-dd'T'HH:mm:ss') + '+00:00';
System.debug('StartDate: ' + startDate2);

I only used newInstanceGmt to create a Datetime instance for my own convenience, but feel free to construct it however suits your needs.

Frequently Asked Questions