+ Start a Discussion

Formatting date in Apex, both the format as well as the value

Hey guys, I need to validate a date field which is being entered by a user via a visualforce page.


The format my code expects is "yyyy-MM-dd".


What is the best way to handle this in apex?

I have done similar stuff in Java before using certain standard classes which are not available in Apex like SimpleDateFormat for example.


Now I can check if the "format" is correct using a regular expression. But I must also prevent users from entering "9999-99-99" which satisfies the format.


I am hoping Salesforce has a good built-in solution.


Thanks, Calvin


Is there a specific reason why you are having your users insert a date as text ?


What I typically do, is have a random sObject with a date field as property, and then expose that date with an <apex:inputfield>. This is also more userfrienly, because it will show the datepicker and be in the same style as the rest of salesforce.





Hey Sdry. Thank you for responding.


I am using a Visualforce page which is shown in our customer portal without using <Apex:pageblock> because it does not allow us to override the native look and feel of salesforce.

I tried using the method you described as its mentioned in quite a few places but the results were not so good.


So I used a customized date picker using javascript as described by Bob Buzzard.



We should allow the users to enter the dates as some may have javascript turned off. A rare chance but definitely possible.

So I was hoping that Apex provided a simple andf efficient means of validating a date object.