[SalesForce] How to format today’s date in this format

How can we format today's date in the following date/time format?

2015-04-29T06:17:44.000-07:00

it represents yyyy-mm-ddThh:mm:sss-UTC

any suggestions will be appreciated.

Thanks in advance.

Best Answer

You can use the DateTime.format(String) method and a Java SimpleDateFormat as the parameter.

System.debug(Datetime.now().format('yyyy-MM-dd\'T\'HH:mm:ss.SSSZ'));

gives:

2015-05-12T15:43:36.358-0700

This will be for the current users local time zone. Note:

"If the time zone cannot be determined, GMT is used."

If you want more control over the timezone you can use the DateTime.format(String, String) method and specify the TimeZone.