Take a look at Java SimpleDateFormat.
system.debug(Datetime.now().format('hh:mmaa')); // 08:24AM
system.debug(Datetime.now().format('hh:mm:ss aa')); // 08:24:07 AM
system.debug(Datetime.now().format('yyyy-MM-dd')); // 2016-05-31
Note that these are methods on Datetime
, so you should not call date()
or time()
on your Datetime
value before doing the formatting, as doing so will change the type to Date
or Time
respectively, and neither of these types have a format
method defined`.