This post explains how to format dates and times using apex.
The below table contains the formatting codes.
| Letter | Date or Time Piece | Examples |
|---|---|---|
| G | Era | G = AD |
| y | Year | yy = 09, yyyy = 2009 |
| M | Month | MM = 08, MMM = Aug, MMMMM = August |
| w | Week in year | w = 35 |
| W | Week in month | W = 3 |
| D | Day in year | D = 235 |
| d | Day in month | dd = 27 |
| F | Day of week in month | F = 2 |
| E | Day in week | E = Thu, EEEEE = Thursday |
| a | AM/PM | a = AM or PM |
| H | Hour in day (0-23) | HH = 23 |
| k | Hour in day (1-24) | kk = 24 |
| K | Hour in am/pm (0-11) | KK=11 |
| h | Hour in am/pm (1-12) | hh = 12 |
| m | Minutes in hour | mm = 30 |
| s | Second in minute | ss = 55 |
| S | Millisecond in second | SSS = 888 |
| z | Time zone | z = EDT, zzzzz = Eastern Daylight Time |
| Z | Time zone offset | Z = -0400 |
Examples
DateTime dt = Datetime.now();
String strTimeInAMorPM = dt.format('MMMMM dd, yyyy hh:mm:ss a');
System.debug('time in am and pm ==> '+strTimeInAMorPM);
String strTimeInWeek = dt.format('MMMMM dd, yyyy EEEE');
System.debug('strTimeInWeek ==> '+strTimeInWeek);
String strTimezone = dt.format('MMMMM dd, yyyy z');
System.debug('strTimezone ==> '+strTimezone);
Output

it's really great
ReplyDelete