Question

I am using the following code to retrieve date and year from NSString. I am printing them in NSLog statements.

NSDate *dateC= [[[NSDate alloc] init] autorelease];
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setLocale:[NSLocale currentLocale]];
[dateFormat setDateFormat:@"MM/dd/yyyy HH:mm"];
dateC = [dateFormat dateFromString:@"04/15/2009 00:00"];  // Only this date gives null date.
[dateFormat setDateFormat:@"MMM dd, yyyy"];
NSLog(@"date = %@",[dateFormat stringFromDate:dateC]);

NSCalendar* calendar = [NSCalendar autoupdatingCurrentCalendar];
NSDateComponents* components = [calendar components:NSYearCalendarUnit|NSMonthCalendarUnit|NSDayCalendarUnit fromDate:dateC];
NSLog(@"year =%d",[components year]);
[dateFormat release];

This code works fine for every date except one that is mentioned in the code.
The output should be:

date = Apr 15, 2009
year =2009

But the output is:

date = (null)
year =2001

Please help me why am I getting this weird behaviour?
NOTE: I am using Xcode 4.6.2 and iOS 6.1

Était-ce utile?

La solution

Please try this exact code. Also note the section under Fixed Formats in the Date Formatters Guide, linked to in the NSDateFormatter class description.

// NSDateFormatter Class Description says:
// Note that although setting a format string (setDateFormat:) in principle specifies an
// exact format, in practice it may nevertheless also be overridden by a user’s
// preferences—see Data Formatting Guide for more details.
NSLocale *locale;

NSLocale *curLocale = [NSLocale currentLocale];
NSLocale *usaLocale = [[NSLocale alloc] initWithLocaleIdentifier:@"en_US"];
if([curLocale.localeIdentifier isEqualToString:usaLocale.localeIdentifier]) {
    locale = [[NSLocale alloc] initWithLocaleIdentifier:usaLocale.localeIdentifier];
    NSLog(@"Created a new one");
} else {
    NSLog(@"USed the old one");
    locale = usaLocale;
}
assert(locale);

NSDate *dateC= [[NSDate alloc] init];
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setLocale:locale];
NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
assert(calendar);
[dateFormat setCalendar:calendar];
[dateFormat setDateFormat:@"MM/dd/yyyy HH:mm"];

dateC = [dateFormat dateFromString:@"04/15/2009 00:00"];  // O
NSLog(@"DATE: %@", dateC);

Autres conseils

If it is displaying a different hour you may need to set the default timezone (this happens only after ios7)

[dateFormat setTimeZone:[NSTimeZone timeZoneWithAbbreviation:@"GMT"]];
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top