I am trying to retrieve hour from a datetime field. I am running a SOQL query and retrieving a set of values in my apex class and looping through them in my visualforce something like  

<apex:repeat var="arr" value="{!arrivals}">

 {!arr.Pickup_Time__c} where arrivals is my soql querry in apex which retrieves a set of values.

Pickup_Time__c is a datetime field and I want to get only hour out of it.

I don't want to use formula fields as they are other issues of DST, timezone etc.

Can any help me with this.



You can do this in two ways

  1. Through Visualforce Page:

<apex:outputText value="{0,date,HH}"> <apex:param value="{!arr.Pickup_Time__c}" /> </apex:outputText>

This will only show you the hour time within the whole datetime.

If you want to specify the condition, you can do like below...

<apex:outputText value="{!IF(VALUE(MID(Text(arr.Pickup_Time__c),12,2))>=12,'PM','AM')}">

This will check for the Hour value and based on the value, it will print accordingly. you can use or show the values as per your requirement level.

  1. Through Controller

for (YourObject obj: ListofObjectValues) {
    List < Integer > hourTime = new List < Integer > ();
    for (Integer inte: hourTime) {
        if (inte >= 12 && inte <= 20) {
            System.debug('Do some process');
        } else {
            System.debug('Do another process');

The choice can be based on your requirement and based on your way of generating your output.
Hope this might helps...

  • Thanks Subhash, I did something similar to the controller approach suggested and it works fine. – Bob Gali Jul 6 '16 at 0:50
  • The issue with the first approach using visualforce is that it returns the hour in UTC format and it makes things difficult for me as I had to take in to account DST and other things. – Bob Gali Jul 6 '16 at 0:51

Well, you just need hour() method of Datetime. To get hour of an Datetime field in apex you just need to write;

Integer hourOfPickupTime = arr.Pickup_Time__c.hour();

hour() method returns integer value. For more info on method; Datetime class

  • Thanks for the response. I actually want to use the hour value for comparison. Say for ex: if hour value is in between 12 to 20 hours, do something. – Bob Gali Jul 4 '16 at 10:16
  • your method should work fine but I am not sure on how to use it when I am inside a loop like this :<apex:repeat var="arr" value="{!arrivals}"> – Bob Gali Jul 4 '16 at 10:35

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.