Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
644 views
in Technique[技术] by (71.8m points)

ios - 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...