3

I have a dateTime field Session_Date_Time__c I want to extract only time from this field. I have tried using

Session_Date_Time__c.time() 

but it gives the result as

 06:22:00.000z

But i want the result as

06:22:00

Any help would be appreeciated. Thanks in advance!!!!!

2 Answers 2

8

You can do it like this :

String s = Session_Date_Time__c.format('HH:mm:ss') 

The DateTime methods : https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_methods_system_datetime.htm

2
  • 2
    Its worth mentioning that format(dateFormatString) will return the time in the users local. If the code is executed by 2 users with different locals 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.
    – BarCotter
    Commented Jun 25, 2015 at 10:02
  • 2
    @BarCotter : you're totally right ! Thanks for mentionning it.
    – SF_user
    Commented Jun 25, 2015 at 10:19
0

Another way to do it if you need the hour and minutes in integer:

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

P.S: As mentioned, it returns value in current user's locale, so use GMT related methods to get it in specific timezone: hourGMT(), minuteGMT(), secondGMT()

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .