How to get time from a Datetime field in Apex

Method 1

Datetime dt = System.now();
String hm = dt.format('HH:mm:ss');
System.debug(hm);

Method 2

Datetime dt = System.now();
Integer hm = dt.hour();
Integer mm = dt.minute();
System.debug(hm+','+mm);

Important Notes

  • Both methods returns the time in the user’s locale. If the code is executed by 2 users with different locales and the same DateTime it will return 2 different times. format(dateFormatString, timezone) or formatGmt(dateFormatString) could be used if you wanted the time to be consistent regardless of the users local. 
  • First method is good if we need to print on UI.
  • Second method is good if you need value in Integer and you want to do further calculations.