Reputation: 4551
I am testing some dateFormatter and i have a problem with a simple
formatter :
- (void)testDate {
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"dd/MM/yyyy"];
NSLocale *locale = [[NSLocale alloc] initWithLocaleIdentifier:@"fr_FR"];
[dateFormatter setLocale:locale];
NSString *stringDate = @"23/03/1";
NSDate *date = [dateFormatter dateFromString:stringDate];
XCTAssertTrue(date == nil);
}
My tests is red because the date is not nil. When i print the date :
(lldb) po date
0001-03-22 23:50:39 +0000
The NSDateFormatter is padding the date string ( 1 ----> 0001).I don't want this padding. Do you think that it's the correct behaviour of the NSDateFormatter ? ( is it a bug in the NSDateFormatter class ? ). How i can avoid this ?
Thanks
Upvotes: 1
Views: 107
Reputation: 437381
I don't think there's a good answer to why is @"23/03/1"
considered a valid date with a formatter of @"dd/MM/yyyy"
. That's just how it works. But if you want to test to see if it's in ##/##/####
format, you could do:
NSRange range = [stringDate rangeOfString:@"^\\d{2}/\\d{2}/\\d{4}$" options:NSRegularExpressionSearch];
XCTAssert(range.location == NSNotFound, @"Not in ##/##/#### format");
Clearly, you'll have to combine that with the NSDateFormatter
test to make sure that the values are reasonable, too, but the above will test the number of digits.
Upvotes: 1
Reputation: 273
My guess is that as "dd/MM/yyyy" is just a format, when NSDateFormatter
processes it, parses given date as 3 numbers and makes transition to date. So "1" is just transferred to "0001".
Upvotes: 0
Reputation: 112857
The date formatter is only being used for parsing the string date to an NSDate
.
The lldb po
command just formats the date based on what some Apple developer thought would be good and it just for debugging. Internally NSDate
uses a proprietary format we believe to be the number of seconds since the first instant of 1 January 2001, GMT.
What you want is to use the date formatter to format the date into the string format you want.
Example code using the format string in the question code:
NSString *dateString = [dateFormatter stringFromDate:date];
NSLog(@"dateString: %@", dateString);
Output:
dateString: 23/03/1999
Add an output date format to meet your needs.
Upvotes: 0