Wednesday 18 August 2010

Displaying different date formats on Visualforce pages.

A common requirement of a Salesforce application is to display date and time information. What is not so common, is how this information needs to be displayed.

Varying the format of a dateTime field inside a Visualforce page is quite straightforward. It involves wrapping the field in a mask and then passing the data as a parameter, like so:

Page:
<apex:outputText value="{0,date,{!dateFormat}}">
     <apex:param value="{!myDateTime}" />
</apex:outputText>

In order to illustrate how this works, I have constructed a page and controller with a few samples. Below is a screenshot of the page displaying a single date (31st December 2010, 23:59:59) in various different formats. The first column of the table shows the string used as the date format mask, whilst the second column shows how that date appears when the mask is applied to the date.


Note that for formats that include literal text, escape characters are required in the controller so that the result renders properly. In my example, Day of the year has to be written as \'Day of the year\' in the formatting String. For all those interested, here is the page and controller code I used to construct the page:

Controller:
public class DateFormattingController {

  Datetime myDateTime = datetime.newInstance(2010, 12, 31, 23, 59, 59);

  List<String> dateFormats = new List<String> {
     'dd.MM.yy HH:mm:ss',
     'MMM-dd-yyyy hh:mm a',
     'EEEEE dd MMMMM yyyy G',
     'E hh:mm:ss:SSS z',
     'zzzzz (Z), \'Day of the year:\' D' 
  };
   
  public DateTime getMyDateTime(){
    return myDateTime;
  }

  public List<String> getDateFormats(){
    return dateFormats;
  }
}

Page:
<apex:page controller="DateFormattingController">
    
    <apex:sectionHeader title="Date Formatting"/>
    
    <apex:outputText value="Standard Output Format: {!myDateTime}"/>
    
    <apex:pageBlock >
        <apex:pageBlockTable value="{!dateFormats}" var="dateFormat">
            <apex:column headerValue="Date Format" value="{!dateFormat}"                                   width="50%"/>
            <apex:column headerValue="Output" width="50%">
                <apex:outputText value="{0,date,{!dateFormat}}">
                    <apex:param value="{!myDateTime}" />
                </apex:outputText>
            </apex:column>
        </apex:pageBlockTable>
    </apex:pageBlock>
    
</apex:page>

See Paul's Salesforce Blog for the full date format letter table. Any missing formats or unsure how to construct a particular format, leave me a comment on the post and I'll see what I can do!