27

In Salesforce, if I'm binding a date into a VisualForce page, how do I apply custom formatting to it?

Example:

<apex:page standardController="Contact">
  <apex:pageBlock title="Test">
      <p>{!contact.Birthdate}</p>
  </apex:pageBlock>                   
  <apex:detail relatedList="false" />
</apex:page> 

This will output a date in the default format:

Thu Jul 01 09:10:23 GMT 2009

How do I get it (for example) into dd/mm/yyyy format, like this:

01/07/2009

(Hopefully this is a fairly easy question, but to get the Salesforce community going on here I figure we need a few easy questions.)

codeulike
  • 22,514
  • 29
  • 120
  • 167

2 Answers2

51
<apex:outputText value="{0,date,MM'/'dd'/'yyyy}">
    <apex:param value="{!contact.Birthdate}" /> 
</apex:outputText>

link to full doc: http://www.salesforce.com/us/developer/docs/pages/Content/pages_compref_outputText.htm

donjay
  • 150
  • 6
Ryan Guest
  • 6,080
  • 2
  • 33
  • 39
  • 3
    Using this approach you can use the full JAVA date formatting classes to format: datetimes, numbers and currency. – Daveo Apr 10 '10 at 08:05
  • Good to know I've been looking for this for a while! Thank you – Meow Nov 18 '10 at 01:23
  • 2
    Can you post a link for documentation? I'd like to know what the first two parameters in apex:outputText (0,date) mean. Thanks. – Pablo Venturino Jun 23 '11 at 20:56
  • 1
    How do you get this formating to take the users timezone into account and display that time in their local timezone instead of GMT? – Keith Mancuso May 20 '13 at 22:17
3

The answer seems to depend on context. I have one VF page which pre-populates the Subject line of a task with the value of NOW(). To record it with the user's Locale settings, I included methods in the controller to format date and datetime fields, along these lines:

  Datetime myDT = Datetime.now(); 
  String myDate = myDT.format();

But just now in another VF page where I'm merely displaying a datetime field, I confirmed that SFDC handled formatting based on the user's Locale setting. That was in this context, where cm.CampaignMembers is a variable from the controller:

    <apex:column>
      <apex:pageBlockTable value="{!cm.CampaignMembers}" var="cmp" >
        <apex:column headerValue="" value="{!cmp.Campaign.Name}" />
        <apex:column headerValue="" value="{!cmp.Status}"  />
        <apex:column headerValue="" value="{!cmp.FirstRespondedDate}" />
        <apex:column headervalue="" value="{!cmp.CreatedDate}"  />
      </apex:pageBlockTable>
    </apex:column>