Become a MacRumors Supporter for $50/year with no ads, ability to filter front page stories, and private forums.

satyam90

macrumors regular
Original poster
Jul 30, 2007
242
0
Bangalore, India
I have a textfield where user enters "MM/dd/yyyy" format of date.
I want to convert this into date. If user enters date correctly, it is working fine. If by chance user enters date in "dd/MM/yyyy", it is not returning date properly. I know that in the following code we are using "setDateFormat". My question is that what will be NSDate* dateOfBirth holding if user enters string in wrong format? Why is it not throwing any error or exception?
Code:
NSDateFormatter* dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"MM/dd/yyyy"];
NSDate* dateOfBirth = [dateFormatter dateFromString:[dob text]];
 
The method simply returns nil if it can't create a date object. You could set up an other formatter with the days/months reversed and try again.
Code:
// Trying to create date from invalid date string.

if ( !dateOfBirth) {
	// Reverse the day/month order in the formatter and try again.
}

if ( !dateOfBirth) {
	// User entered something not at all resembling a date.
}

It would be a good idea to reformat the textview to a longer style (Aug 30, 2009) as soon as the focus moves from it, so the user may see that the date was properly interpreted. Or highlight the textview in red or something, so the user can see it's invalid.
 
Register on MacRumors! This sidebar will go away, and you'll see fewer ads.