简体   繁体   中英

dateFromString returns nil every time format possibly wrong?

I am trying to use date from string method like below:

var dateNow = self.tags![indexPath.row].date!
let timeZone = NSTimeZone(name: "UTC")
let df = NSDateFormatter()
df.locale = NSLocale.currentLocale()
df.timeZone = timeZone
df.dateFormat = "yyyy-MM-ddThh:mm"
let date: NSDate = df.dateFromString(dateNow)! //this is nil and throws an unwrapping error

The date is formatted like this

dateNow String  "2015-04-19T17:00:42.205Z"  

Im guessing maybe that is formatted wrong but I have no idea how to write the df.dateFormat

您只需要按照以下方式设置其格式:

df.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZ"

Yet another way to get nil is if you use hh and your hours are on the 24 hr clock and > 12, in that case, you need HH (or H, for zero-padded).

That is:

Format: yyyy-MM-DD hh:mm:ss , string: "2016-03-01 13:42:17" will return nil .

Format: yyyy-MM-DD HH:mm:ss , string: "2016-03-01 13:42:17" will return the date you expect.

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