How can I parse a string that represents a date and/or time using iPhone SDK if I do not know the format? I am building an application that will allow a range of possible dates and times to be used, and I don’t want it to fail because the format was “01/01/2001” instead of “01-01-2001”, etc. Time may or may not be included.
Is there any way to do this? I have tried using NSDateFormatter with date and time styles set to “NoStyle”, and setLenient = YES, but it still fails to parse the simplest of strings: “1/22/2009 12:00:00 PM”
I have no way of knowing the format in advance, I need a method that will heuristically determine the format.
I am coming from a .NET background, where this is as simple as new DateTime(string_in_any_format); but I have no idea how to do this in Obj-C.
Unfortunately,
NSDateFormatteron the iPhone isn’t that smart. You need to give it a little guidance. When you set both the date and time styles toNoStyleit expects to see neither a date nor time. You’ll need at least one of them set to some other style. You can do something like the following and it should work fine (it does for me).