Graham Barnard

Salesforce Date Formatting in Apex




Salesforce Date Formatting in Apex

Posted by Graham Barnard on .

Formatting Salesforce dates in Apex is straightforward. The most challenging part is understanding how the date syntax formatting works and that will only take you five minutes to figure out. So why am I writing this blog post? Because I always forget how this works and I’m sick and tired of regoogling this and not finding good Apex specific examples.

Datetime Format Methods
Date Format Syntax

Datetime to String

String dateFormat = 'yyyy-MM-dd\'T\'HH:mm:ss\'Z\'';

DateTime dt =;
String dateString = dt.format(dateFormat);
System.debug(dateString); // 2016-02-29T22:30:48Z

Date to String

String dateFormatString = 'yyyy-MM-dd';

Date d =;
Datetime dt = Datetime.newInstance(d.year(), d.month(),;
String dateString = dt.format(dateFormatString);
System.debug(dateString); // 2016-02-29

Useful Examples

// 2016-02-29'yyyy-MM-dd');

// 2016-02-29T23:50:24Z873'yyyy-MM-dd\'T\'HH:mm:ss\'Z\'SSS');

// 2016.02.29 AD at 23:52:20 EST'yyyy.MM.dd G \'at\' HH:mm:ss z');

// Mon, 29 Feb 2016 23:54:22 -0500'EEE, d MMM yyyy HH:mm:ss Z');

// Today is Monday'\'Today is\' EEEE');

// Tuesday March 01, 2016 is the 61 day of the year'EEEE MMMM dd, YYYY \'is the\' D \'day of the year\'');

// Tuesday March 01, 2016 is the 1 day of the month'EEEE MMMM dd, YYYY \'is the\' d \'day of the month\'');


Graham Barnard

Senior Salesforce Developer