2

I'm receiving a string containing a date. I want to check if it has the format "dd/MM/yyyy". Right now I'm using code that I found in this same page:

NSDate *date = [dateFormatter dateFromString:dateString];
if(date == nil) {
    correctFormat = false;
}

It works for some cases, but for example, if I input "22-12-1996" instead of "22/12/1996", it creates the date anyway. Is there another way that's consistent?

Clay Bridges
  • 11,602
  • 10
  • 68
  • 118
Jaime Alcántara Arnela
  • 2,062
  • 5
  • 25
  • 56

1 Answers1

2

NSDateFormatter handle format of string dates.

Instances of NSDateFormatter create string representations of NSDate objects, and convert textual representations of dates and times into NSDate objects.

Try this and see:

// Set date format according to your string date format
// e.g.: For, 
// 22-12-1996 -> @"dd-MM-yyyy"
// 22/12/1996 -> @"dd/MM/yyyy"
// 1996-12-22 03:45:20 -> @"yyyy-MM-dd HH:mm:ss"

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
dateFormatter.dateFormat = @"dd/MM/yyyy";
//dateFormatter.dateFormat = @"dd-MM-yyyy";

NSDate *date = [dateFormatter dateFromString:dateString];
if(date == nil) {
    correctFormat = false;
}
NSLog("Date: %@",date);

Note: Each pairs of characters in date format relates relevant date component with date instance. You can create any type of date format using date string pattern.

Here is document by Apple: Date Formatters

  • Date (Day): dd
  • Month: MM or MMM or MMMM
  • Year: yy or yyyy

Here is list of date formats: Date Formats

Clay Bridges
  • 11,602
  • 10
  • 68
  • 118
Krunal
  • 77,632
  • 48
  • 245
  • 261