7

I was wondering if there is an apex date or datetime function to format a date/time to the ISO formatted timestamp "2007-04-05T12:30-02:00" or would this have to be created by another means?

Thanks.

2 Answers 2

21

In Apex you can use the DateTime format(string dataFormat) or format(string dataFormat, string timezone) methods. It accepts a dataFormat string, which corresponds to a Java simple date format. You will need to define the correct format for ISO 8601.

Also, take into account the timezone of the DateTime. In the example below I've used formatGMT to avoid the timezone offset.

System.debug(datetime.now().formatGMT('yyyy-MM-dd\'T\'HH:mm:ss.SSS\'Z\''));

Alternatively, you could use the JSON serializer.

System.debug(json.serialize(datetime.now()));
1
  • 3
    note with json.serialize(): It seems to wrap the returned string in singe quotes.
    – NSjonas
    Sep 8, 2016 at 21:04
1

For anyone reading this now, if you want the time zone, using Java SimpleDateFormat, you can get the +/-hh:mm timezone offset value:

System.debug(datetime.now().format('yyyy-MM-dd\'T\'HH:mm:ss.SSSXXX', 'America/Los_Angeles'));

Output: 2021-01-15T17:30:22.735-08:00
1
  • Note that you can use System.debug(datetime.now().format('yyyy-MM-dd\'T\'HH:mm:ss.SSSXXX', 'UTC')); to get UTC datetime with no offset Jun 11, 2021 at 2:17

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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