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.
Letter | Component | Example |
---|---|---|
y | Year | 2020 |
M | Month in year | 3 |
w | Week in year | 11 |
W | Week in month | 2 |
D | Day in year | 68 |
d | Day in month | 8 |
E | Day name | Sunday |
u | Day of week (1 = Monday, 7 =Sunday) | 7 |
a | AM/PM | PM |
H | Hour (0 – 23) | 15 |
K | Hour (0 – 11) | 3 |
m | Minute | 45 |
s | Second | 12 |
S | Millisecond | 71 |
z | Time Zone | PDT |
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:
String | Component | Example |
---|---|---|
y | Year (four digit) | 2020 |
yy | Year (two digit) | 20 |
M | Month (no leading zero) | 3 |
MM | Month (leading zero) | 03 |
MMM | Month (abbreviated) | Mar |
MMMM | Month (not abbreviated) | March |
E | Day name (abbreviated) | Sun |
EEEE | Day name (not abbreviated) | Sunday |
z | Time Zone (abbreviated) | PST |
zzzz | Time 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.