Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
417 views
in Technique[技术] by (71.8m points)

Converting an ISO 8601 timestamp into an NSDate: How does one deal with the UTC time offset?

I'm having trouble converting an ISO 8601 timestamp into an NSDate. I tried to use NSDateFormatter, but I can't get it to work with the UTC time offset that appears on the end of the timestamps. To explain, I would like to convert a timestamp such as the following into an NSDate: 2011-03-03T06:00:00-06:00. My question is: How do I deal with the "-06:00" part? I tried using yyyy-MM-dd'T'HH:mm:ssZ as my date format string but it doesn't work. Any suggestions?

question from:https://stackoverflow.com/questions/5185230/converting-an-iso-8601-timestamp-into-an-nsdate-how-does-one-deal-with-the-utc

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

No need to remove the :'s. To handle the "00:00" style timezone, you just need "ZZZZ":

Swift

let dateString = "2014-07-06T07:59:00Z"

let dateFormatter = NSDateFormatter()
dateFormatter.locale = NSLocale(localeIdentifier: "en_US_POSIX")
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZZZZ"
dateFormatter.dateFromString(dateString)

Objective-C

NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
dateFormat.locale = [[NSLocale alloc] initWithLocaleIdentifier:@"en_US_POSIX"];
NSString *input = @"2013-05-08T19:03:53+00:00";
[dateFormat setDateFormat:@"yyyy-MM-dd'T'HH:mm:ssZZZZ"]; //iso 8601 format
NSDate *output = [dateFormat dateFromString:input];
NSLog(@"Date output: %@", output);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...