I have a string that contains a .net datetime (rawData) and I am trying to parse it into a NSDate
object using a NSDateFormatter
. I think my format string might be wrong or something because the dateFromString:
method is returning nil. Can any one please help me figure out the issue here?
NSString *rawData = @"2009-10-20T06:01:00-07:00";
//Strip the colon out of the time zone
NSRange timezone = NSMakeR开发者_运维问答ange([data length] - 3, 3);
NSString *cleanData = [rawData stringByReplacingOccurrencesOfString:@":" withString:@"" options:NSCaseInsensitiveSearch range:timezone ];
//Setup a formatter and parse it into a NSDate object
NSDateFormatter *df = [[NSDateFormatter alloc] init];
[df setDateFormat:@"yyyy-MM-ddThh:mm:ssZ"];
NSDate *result = [df dateFromString: cleanData]; //Result is nil
With iOS 6.0 and higher, representation for timezone with colon separating hour and minutes is added.(ZZZZZ
or fallback z
)Refer the following link Date Formats
This makes the code very simple
NSString *dateString = @"2009-10-20T06:01:00-07:00";
NSDateFormatter *dateFormatter = [NSDateFormatter new];
[dateFormatter setDateFormat:@"yyyy-MM-dd'T'HH:mm:ssZZZZZ"];
NSDate *date = [dateFormatter dateFromString:dateString];
NSLog(@"%@",date);
I just tested this code and it's work:
NSString *rawData = @"2009-10-20 06:01:00-07:00";
//Strip the colon out of the time zone
NSRange timezone = NSMakeRange([rawData length] - 3, 3);
NSString *cleanData = [rawData stringByReplacingOccurrencesOfString:@":" withString:@"" options:NSCaseInsensitiveSearch range:timezone ];
// Get rid of the T also
cleanData = [cleanData stringByReplacingOccurrencesOfString:@"T" withString:@" "];
//Setup a formatter and parse it into a NSDate object
NSDateFormatter *df = [[NSDateFormatter alloc] init];
[df setDateFormat:@"yyyy-MM-dd HH:mm:ssZZZ"];
NSDate *result = [df dateFromString: cleanData]; //Result is ni
NSLog(@"Result %@", result);
Couple of notes
- Get rid of the T.
- 24-Hour format for hours is HH
Try this:
NSDateFormatter *df = [[[NSDateFormatter alloc] init] autorelease];
df.dateFormat = @"yyyy-MM-dd'T'HH:mm:ss.SS";
df.locale = [[[NSLocale alloc] initWithLocaleIdentifier:@"en_GB"] autorelease];
NSDate *result = [df dateFromString:rawData];
Looks like .NET outputs dates as ISO 8601 strings? For parsing these I use an open source NSFormatter subclass written by Peter Hosey, which you can find here. Unfortunately it's not trivial to parse these correctly using a simple dateFormat string. See also this question.
精彩评论