Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Salesforce Apex: ISO Timestamp Format Function

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.

like image 790
SalesforceQueries Avatar asked Aug 31 '13 17:08

SalesforceQueries


People also ask

What is the format of date/time field in Salesforce?

Date and Time Stored in Salesforce Salesforce uses the ISO8601 format YYYY-MM-DDThh:mm:ss.SZ for date/time fields, which stores date/time in UTC.

How do I get a date in YYYY MM DD in Apex?

Date d = date. today(); String dt = DateTime. newInstance(d. year(),d.


2 Answers

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()));
like image 62
Daniel Ballinger Avatar answered Sep 27 '22 23:09

Daniel Ballinger


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
like image 38
apps Avatar answered Sep 27 '22 22:09

apps