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
chen young
Ranch Hand
Joined: Sep 09, 2005
Posts: 178
posted
0
Thanks
Mustafa Musaji
Ranch Hand
Joined: May 03, 2008
Posts: 52
posted
0
You may also want to check out this Thread in the intermediate forum
Dear All,
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!
Sunil Kumar
Ranch Hand
Joined: Apr 24, 2007
Posts: 76
posted
0
ramya narayanan wrote:There is likely both may not be equal .
Not sure if this case exists. Did you find one?
ramya narayanan
Ranch Hand
Joined: Oct 06, 2008
Posts: 338
posted
0
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.
Regards
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.
ramya narayanan
Ranch Hand
Joined: Oct 06, 2008
Posts: 338
posted
0
Thanks Rob Prime for once again patiently explaining the best practices !
My Best Regards(to you)!
Sunil Kumar
Ranch Hand
Joined: Apr 24, 2007
Posts: 76
posted
0
Thanks Rob!
I agree. Here's the link: http://ej-technologies/jprofiler - if it wasn't for jprofiler, we would need to
run our stuff on 16 servers instead of 3.