Check NSString for specific date format

I have an NSString and I need to verify that it is in this MM / DD / YY format. Then I need to convert this to NSDate. Any help on this would be greatly appreciated. Sidenote - I searched around and people suggest using RegEx, I never used this and don't quite understand it at all. Can someone please give me a good resource / explanation.

+6
source share
4 answers

Use NSDateFormatter for both tasks. If you can convert the string to a date, it will be in the correct format (and you already have the result).

+6
source
 NSString *strDate1 = @"02/09/13"; NSString *strDate2 = @"0123/234/234"; NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init]; [dateFormatter setDateFormat:@"dd/MM/yy"]; [dateFormatter setTimeZone:[NSTimeZone timeZoneWithAbbreviation:@"GMT"]]; NSDate *dateFormat1 = [dateFormatter dateFromString:strDate1]; NSDate *dateFormat2 = [dateFormatter dateFromString:strDate2]; NSLog(@"%@", dateFormat1); // prints 2013-09-02 00:00:00 +0000 NSLog(@"%@", dateFormat2); // prints (null) 

So, you will find out when it is not formatted correctly if the NSDate is zero. Here's a link to the docs if you need more info: https://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/DataFormatting/Articles/dfDateFormatting10_4.html#//apple_ref/doc/uid/TP40002369-SW1

+7
source

I know this is a late answer, but it cannot always be guaranteed that the string is in this particular date format.

The date format, regular expression, or even a person cannot check certain dates because we don’t know if the user enters β€œmm / DD / yy” or β€œDD / mm / yy”. Typically, in some places you enter the day of the month first, while in other places you enter the month first. So, if they go into 06/09/2013, do they mean September 6th or June 9th?

+2
source

Here is a simple feature for anyone looking for a simple solution.

 - (BOOL) isTheStringDate: (NSString*) theString { NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init]; [dateFormatter setDateFormat:@"yyyy-MM-dd"]; NSDate *dateFromString = [[NSDate alloc] init]; dateFromString = [dateFormatter dateFromString:theString]; if (dateFromString !=nil) { return true; } else { return false; } } 

You must change the formatter below to match the formatting used by your date.

  [dateFormatter setDateFormat:@"yyyy-MM-dd"]; 
+2
source

Source: https://habr.com/ru/post/953095/


All Articles