Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check date format in Objective-C

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?

like image 833
Jaime Alcántara Arnela Avatar asked Jun 16 '26 06:06

Jaime Alcántara Arnela


1 Answers

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

like image 189
Krunal Avatar answered Jun 17 '26 23:06

Krunal



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!