[SalesForce] correct date format on date field dynamically

I am fetching dynamic field values in apex repeat so in these scenario, i am using 1 date field so when i fetch data then it show as a incorrect date format. How is this possible to show date in correct format.

VF Page:-

  <apex:repeat value="{!accessibleFieldsForObjectives}" var="fieldsForObjective" >
      <th>{!$ObjectType[objObjectiveName].fields[fieldsForObjective].Label}</th>
  </apex:repeat>
  <td> <apex:outputLabel value="{!$Label.PopupCommandLinkLabel}"/> </td>
</tr>
<apex:repeat value="{!allSchedules}" var="rec">  
  <tr>
    <apex:repeat value="{!accessibleFieldsForObjectives}" var="fieldsForObjective">
      <td>
         <apex:inputField value="{!rec.sObj[fieldsForObjective]}" style="width: 90px;"/> 
      </td>
</apex:repeat>

Best Answer

You will need to identify the field type in your back-end and to create a map to keep the date fields. So your apex code should look something like this:

public Map <String, Boolean> fieldIsDate {get; set;}

private void populateListOfFields()
{
    fieldIsDate = new Map <String, Boolean> ();

    Map<String, Schema.SObjectField> M;
    M = Schema.SObjectType.Account.fields.getMap();
    for (String fieldName : M.keySet())
    {
        if (M.get(fieldName).getDescribe().getType().toString() == Schema.DisplayType.DATE)
        {
            fieldIsDate.put(fieldName, true);
            continue;
        }

        fieldIsDate.put(fieldName, false);
    }
}

Then in your visualforce page you'll know if the field name is of type date or not, and depending on that you can render the dates in a specific format:

<td>
    <apex:outputText value="{0, date, dd/MM/yyyy}" rendered="{!fieldIsDate[fieldsForObjective] == true}">
        <apex:param value="{!child.sObj[fieldsForObjective]}" name="p0" />
    </apex:outputText>
    <apex:outputField value="{!child.sObj[fieldsForObjective]}" rendered="{!fieldIsDate[fieldsForObjective] == false}" />
</td>
Related Topic