Warning: file_get_contents(https://interactiveties.com/services/objects/posts/20.json): failed to open stream: HTTP request failed! HTTP/1.1 406 Not Acceptable
in /home/intera35/public_html/incl/4.4.0/blog-post-top.php on line 17
Warning: file_get_contents(https://interactiveties.com/services/objects/tags/post/20.json): failed to open stream: HTTP request failed! HTTP/1.1 406 Not Acceptable
in /home/intera35/public_html/incl/4.4.0/blog-post-tags.php on line 11
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.cls
*/
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>
Author
Greg Hacic
I've been working with Salesforce since 2003. Over the years, I've held various roles for a diverse array of salesforce.com customers, created a Salesforce specific ISV, and built numerous applications for the AppExchange. All of these experiences have allowed me to learn quite a bit about building on the platform.