Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check NSString for specific date format

I have a NSString and I need to check that it is in a this specific format MM/DD/YY. I then need to convert that to a NSDate. Any help on this would be much appreciated. Sidenote - I have searched around and people suggest using RegEx, I have never used this and am unclear about it generally. Can anyone point me to a good resource/explanation.

like image 905
HenryGale Avatar asked Sep 03 '13 22:09

HenryGale


3 Answers

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 know when it's not formatted correctly if the NSDate is nil. Here's the 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

like image 197
Dylan Bettermann Avatar answered Oct 07 '22 14:10

Dylan Bettermann


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

like image 22
Wain Avatar answered Oct 07 '22 16:10

Wain


I know that this is a late answer, but it is impossible to always guarantee that a string is in this particular date format.

A date formatter, a regex, or even a human can not verify certain dates, because we don't know if the user is entering "mm/DD/yy" or "DD/mm/yy". It is common in some places to enter the day of the month first, while in other areas you enter the month first. So if they enter "09/06/2013" do they mean "September 6th" or the "9th of June"?

like image 41
lnafziger Avatar answered Oct 07 '22 14:10

lnafziger