1

I am getting nil for some values while using dateFromString in swift. I searched a lot but in vain.

Following is my code:

let strDate = self.sortedDict.valueForKey("TIME").objectAtIndex(indexPath.row).objectAtIndex(0) as? String
        print(strDate);

        let st_date = frmt.dateFromString(strDate!)

        let frmt1:NSDateFormatter = NSDateFormatter()
        frmt1.locale = NSLocale(localeIdentifier: localeStr)
        frmt1.dateFormat = "MMM, dd yyyy hh:mm a"
        if st_date != nil {
            print(st_date)
}

Output console:

    Optional("September, 20 2015 10:00:00")
Optional(2015-09-20 10:00:00 +0000)

Optional("October, 04 2015 10:00:00")
Optional(2015-10-04 10:00:00 +0000)

Optional("October, 04 2015 14:00:00") // nil
Optional("October, 18 2015 15:00:00") // nil
Optional("September, 20 2015 14:00:00") // nil

Optional("September, 27 2015 10:00:00")
Optional(2015-09-27 10:00:00 +0000)
Optional("September, 27 2015 12:00:00")
Optional(2015-09-27 00:00:00 +0000)
Optional("September, 27 2015 14:00:00")

Optional("October, 03 2015 14:00:00") //nil
Optional("October, 03 2015 16:00:00") //nil

The format is same for all date strings still I get nil for few values. Why so? Please help. Where am I getting wrong?

3
  • Optional("September, 27 2015 14:00:00") - That one doesn't return nil? You're sure?
    – gnasher729
    Dec 22, 2015 at 8:07
  • And that's not your actual code, right?
    – gnasher729
    Dec 22, 2015 at 8:08
  • Yeah that's my actual code and it does work for Optional("September, 27 2015 14:00:00")
    – z22
    Dec 22, 2015 at 11:16

1 Answer 1

5

format should be HH for 24 hours even you are getting values only for 12 hours.

frmt1.dateFormat = "MMM, dd yyyy HH:mm a"
2
  • So why does Optional("September, 27 2015 14:00:00") work?
    – gnasher729
    Dec 22, 2015 at 8:07
  • @gnasher729 It might be written problem. It should not work for 12 hours format. Dec 22, 2015 at 8:11

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.