I need to check if date is valid
This is the format of the date: ####-##-## ##:##:## ,for example2008-12-23 09:29:13
I am a bit confused with all the date objects in java Any suggestion regarding how should I check this format ?
I'm not sure if I completely understand how you want to check the date, but you can use SimpleDateFormat to create the format of the date and then parse a date object using the formatter created. Check out the API for SimpleDateFormat or google "date format using Java". You'll find some good examples.
EDIT: Exactly how Sunil has said above! lol, beat me to it!
SCJP 5.0 - Passed
Joined: Sep 09, 2005
Joined: May 03, 2008
You may also want to check out this Thread in the intermediate forum
I've a dummy doubt.
Please don't mind.
In the below code,
datestr is the original date value & testDate(in the if condition after it is executed) is the formatted date.
There is likely both may not be equal .
in that case if block becomes true right & returns false.
So the original date & validated date won't be equal right!
Joined: Apr 24, 2007
ramya narayanan wrote:There is likely both may not be equal .
Not sure if this case exists. Did you find one?
Joined: Oct 06, 2008
No sunil, I want to know what the below code does.
Sunil Kumar wrote:Use simple date format like this
There are two improvements that can be made:
- turn off leniency
- check if the parsing did not ignore the trailing part of the string (ok, you're actually doing that at the end, but it can be a bit more efficient ;))
If the string could not be parsed, then pos.getIndex() will still return 0. If it could be parsed but there is trailing garbage (e.g. "2009-01-13 09:34:00 Hello world!") then pos.getIndex() will be smaller than dateStr.length().
As for no exception, that's because DateFormat.parse(String) uses the same technique:
And if you can avoid an exception, you should always do so.
ramya narayanan wrote:No sunil, I want to know what the below code does.
Parsing a date can remove any trailing garbage, as in the example I described above. This statement checks if the formatted date is equal to the source string. Taking my example, the formatted date would be "2009-01-13 09:34:00" which is not equal to the source.
Joined: Oct 06, 2008
Thanks Rob Prime for once again patiently explaining the best practices !
My Best Regards(to you)!