[SalesForce] Issue with Jquery DatePicker in Visualforce page

I have been facing an issue with the usage of datepicker in my VF page.

VF page:

    <script>
    jQuery(function(){
            var $j = jQuery.noConflict();
            $j("input[id$=expdate]").datepicker({
               changeYear: true,
               changeMonth: true,
               dateFormat: "mm/dd/yy"
            });
          });
</script>

expdate is the id of the field.

<apex:pageBlockSectionItem rendered="{!ISNULL($CurrentPage.parameters.docId)}">
      <apex:outputLabel value="Expiration Date" for="expdate"/> 
      <apex:inputText value="{!expdate}" id="expdate"/>
    </apex:pageBlockSectionItem>

What should I do that the datepicker sets itself according to the user's locale settings? I would like the datepicker to be mm/dd/yy OR dd/mm/yy based on his user locale settings on Salesforce.

Best Answer

The simple way is to grab the data from the object that Salesforce itself populates but this is not a documented API and may change. Wrapping it in fallback code like this ensures your code doesn't completely die if the API is changed:

function getDateFormat() {
    try {
        return UserContext.dateFormat;
    } catch (e) {
        return 'mm/dd/yy';
    }
}

The more complicated approach is to take the results of the format of a known date in Apex and figure out the right formatting string from that and pass it to the client-side JavaScript.

Or just stick to the platform's default date picker. (Though that is only presented for SObject date fields.)

Related Topic