Format DateTime Data in Apex

The DateTime object in Apex includes rich support for formatting dates using Java’s SimpleDateFormat. To format a DateTime, call the format() method and pass it a format string. The following table includes the most common elements you can include in the format string. All examples are using the date and time when I’m writing this — March 8, 2020 at 3:45pm.

LetterComponentExample
yYear2020
MMonth in year3
wWeek in year11
WWeek in month2
DDay in year68
dDay in month8
EDay nameSunday
uDay of week (1 = Monday, 7 =Sunday)7
aAM/PMPM
HHour (0 – 23)15
KHour (0 – 11)3
mMinute45
sSecond12
SMillisecond71
zTime ZonePDT

Repeat Letters to Modify the Presentation

Many of the letters can be repeated to modify the presentation of the component they represent. For example, ‘y’ displays the four digit year 2020, ‘yy’ displays the two digit year 20. Most of the numeric values like M, Month in year will display a leading zero for single digit numbers if you repeat the letter twice. For example the month of March would be ‘M’ = 3, ‘MM’ = 03. Some other variations are as follows:

StringComponentExample
yYear (four digit)2020
yyYear (two digit)20
MMonth (no leading zero)3
MMMonth (leading zero)03
MMMMonth (abbreviated)Mar
MMMMMonth (not abbreviated)March
EDay name (abbreviated)Sun
EEEEDay name (not abbreviated)Sunday
zTime Zone (abbreviated)PST
zzzzTime Zone (not abbreviated)Pacific Standard Time

Some Examples

Datetime.now().format('EEEE MMMM d, y');
Sunday March 8, 2020

Datetime.now().format('K:mm a z');
3:45 PM PDT

I hope that’s helpful.

Leave a Comment