Saturday, April 25, 2020

Format Dates and Time using Apex in Salesforce


This post explains how to format dates and times using apex.
The below table contains the formatting codes.

LetterDate or Time PieceExamples
GEraG = AD
yYearyy = 09, yyyy = 2009
MMonthMM = 08, MMM = Aug, MMMMM = August
wWeek in yearw = 35
WWeek in monthW = 3
DDay in yearD = 235
dDay in monthdd = 27
FDay of week in monthF = 2
EDay in weekE = Thu, EEEEE = Thursday
aAM/PMa = AM or PM
HHour in day (0-23)HH = 23
kHour in day (1-24)kk = 24
KHour in am/pm (0-11)KK=11
hHour in am/pm (1-12)hh = 12
mMinutes in hourmm = 30
sSecond in minutess = 55
SMillisecond in secondSSS = 888
zTime zonez = EDT, zzzzz = Eastern Daylight Time
ZTime zone offsetZ = -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

1 comment: