Convert String to NSDate

Discussion in 'Mac Programming' started by satyam90, Aug 30, 2009.

  1. satyam90 macrumors regular


    Jul 30, 2007
    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?
    NSDateFormatter* dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"MM/dd/yyyy"];
    NSDate* dateOfBirth = [dateFormatter dateFromString:[dob text]];
  2. rossipoo macrumors regular

    Jun 7, 2009
    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.
    // 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.

Share This Page