What's the simplest way to parse RFC3339 date string in iOS?

梦想与她 提交于 2019-12-05 12:18:30

The pure stuff-that-comes-with-Cocoa way is exactly what you're doing. You can make this method both shorter and faster by creating the date formatters elsewhere, probably in init, and using/reusing them in this method.

You need two formats because fractional seconds are optional, and the timezone should be Z5, not Z. So you create two formatters with formats

@"yyyy'-'MM'-'dd'T'HH':'mm':'ssX5"
@"yyyy'-'MM'-'dd'T'HH':'mm':'ss.SSSSSSX5"

and try them both. That's obviously for RFC3339; your strings might not be in that format. Glad you didn't ask for RFC822 which is a pain to do correctly. But you should really have a method first that returns NSDate, because most uses don't actually need a string formatted for the user.

I had some problems with parsing RFC 3339 in Obj-c since the fractional seconds and zone seems to be optional.

The most reliable function that I found was this Gist (of which I am not the author): https://gist.github.com/mwaterfall/953664

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!