Locale Formatted Date Component

Years ago I wrote a post about how to use the User's locale settings in order to render a properly formatted DateTime value within a Visualforce page. Today I needed a locale based date value to render in Visualforce. I went out to that old post and reviewed it because I needed a place to begin coding.

I decided that although that code was a decent starting point I could reduce the overall number of lines of code significantly. This is the result of that code revision.

First, we need a controller for the Visualforce component. Navigate to Setup > Develop > Apex Classes. Click the New button on that page. Copy and paste the following Apex code.

/*
	Created by: Greg Hacic
	Last Update: 11 August 2015 by Greg Hacic
	Questions?: greg@interactiveties.com
	
	Notes:
		- controller for the localeFormattedDate Visualforce component
		- tests located at localeFormattedDateTest.class
*/
public class localeFormattedDate {
	
	public Date dateValue {get;set;} //property that reads the date value from the component attribute tag
	
	public String getFormattedDate() {
		String dateFormatted; //variable for the date
		if( dateValue != null ) { //if the dateValue variable is not null
			dateFormatted = dateValue.format(); //the dateValue as a string using the locale of the User
		}
		return dateFormatted; //return the string
	}

}

Next we require the component itself. Navigate to Setup > Develop > Components. Click the New button on that page. Copy and paste the following Visualforce component code.

<apex:component access="global" controller="localeFormattedDate">
<!--
	Created by: Greg Hacic
	Last Update: 11 August 2015 by Greg Hacic
	Questions?: greg@interactiveties.com
	
	NOTES:
		- when adding to your Salesforce org set the name of component to localeFormattedDate
-->
<apex:attribute assignTo="{!dateValue}" description="The Date value to be rendered based upon the user's locale" name="dateProvided" type="Date"></apex:attribute>
{!formattedDate}
</apex:component>

Now you need to know how to call the controller:

<c:localeFormattedDate dateProvided="{!Today()}"></c:localeFormattedDate>

Automated Exchange Rates in Salesforce.com

Reduce Repetitive Tasks, Eliminate Errors & Free Up Your Administrators.

Birthday Reminders for Salesforce.com

It might lead to a sale. Or it might make you feel good.