开发者

convert string to NSDate object [closed]

As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will开发者_Python百科 likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance. Closed 10 years ago.

I am getting string "2011-09-24T00:30:00.000-07:00" from webservice. I don't know the what is this format and want to convert in date object in objective-c.

So any know how to convert this string to date.

Thank you very much


There is a small problem obtaining the date/time from this format, the ':' in the timezone, that will need to be removed, Apple does not handle this case nor it is a proper UTS format. Here is an example:

NSString *dateString = @"2011-09-24T00:30:00.000-07:00";
dateString = [dateString stringByReplacingOccurrencesOfString:@":" withString:@"" options:0 range:NSMakeRange(dateString.length-3, 1)];
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:@"yyyy-MM-dd'T'HH:mm:ss.SSSZZZ"];
NSDate *date = [formatter dateFromString:dateString];
NSLog(@"date: %@", date);

NSLog output: date: 2011-09-24 07:30:00 +0000

As a test displaying the date just created:

NSString *testDateString = [formatter stringFromDate:date];
NSLog(@"date: %@", testDateString);

NSLog output: date: 2011-09-24T03:30:00.100-0400

Note that the time and time zone have been converted to my local time zone by NSLog, taking both changes into consideration the date/time are the same as the original.


The string format typically used by web services for date/time representation is RFC 3339

It cannot be trivially converted to and from NSDate because it may include a variety of information not representable just by NSDate (such as time offset from UTC, and date with no time specified.)

There are classes which map RFC 3339 strings to and from native Cocoa types, such as this. You may be able to get by with a simpler conversion that takes shortcuts, but for robust code, use a class written specifically to handle the representation.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜