简体   繁体   中英

dateFromString returns nil for some values

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?

格式应该是24小时的HH ,即使您只获得12小时的值。

frmt1.dateFormat = "MMM, dd yyyy HH:mm a"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM