Search code examples
xcodeswiftnsdateformatterrfc1123

(Swift) Using NSDataFormatter with a medium style string to get date


I seem to be stuck here and I have been wasting way too much tome on this.

What I have is a string that is in the RFC 1123 format that I would like to get a date out of, but not matter what I do, I get a nil result;

 let dateFormat = NSDateFormatter();

    dateFormat.dateStyle = .MediumStyle;
    dateFormat.dateFormat = "EEE',' dd MMM yyyy HH':'mm':'ss z";
    dateFormat.locale = NSLocale.systemLocale();
    dateFormat.timeZone = NSTimeZone(abbreviation:"GMT");
    var currentDate = dateFormat.dateFromString("Sun, 28 Jun 2015 04:30:54 GMT");

I am not sure what I am missing, if I changed the MMM to MM and make Jun 06, then it works. It seems to be only this instance. I have tried moving the order of how dateFormat gets created, and still I get no results. Any help on this matter would greatly be appreciated


Solution

  • I think you have confused the formatter. You don't need to set anything except the format string, because the formatter's job is to learn those other settings from the string it reads.

    let dateFormat = NSDateFormatter()
    dateFormat.dateFormat = "EEE',' dd MMM yyyy HH':'mm':'ss z"
    var currentDate = dateFormat.dateFromString("Sun, 28 Jun 2015 04:30:54 GMT")
    
    // "Jun 27, 2015, 11:30 PM"
    

    If you do as above, it will return an NSDate? from the date string you provided.