Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
626 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 Answer

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"

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...