How to get time from a Datetime field in Apex

Method 1

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

Method 2

Datetime dt =;
Integer hm = dt.hour();
Integer mm = dt.minute();

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.