简体   繁体   中英

Format string to NSdate in Swift

My string is = "2015-08-26 14:21:40.557"

My code:

var dateFormatter = NSDateFormatter()
        dateFormatter.dateFormat = "yyyy-MM-dd hh:mm:Z"

        var date = dateFormatter.dateFromString(creationDateStr as String )

I get a nil date , what's the right format?

The format must match your input string exactly, so

dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss.SSS"

will do the job.

Note that Z is used for the timezone, not for (milli)seconds.

And HH is for 24 hours; hh only allows values between 01 and 12 and is usually paired with a to indicate AM/PM.

        var dateFormatter = NSDateFormatter()
        dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss.SSS"

        var date = dateFormatter.dateFromString(creationDateStr as String )

Will return nil if your string is not in this date format. (ex. "5/26/2015" will return nil but "2015-05-26 12:30:00.123" will return a nsdate)

The format is incorrect for the string you are attempting to parse.

The correct format is:

"yyyy-MM-dd HH:mm:ss.SSS"

Parsing an incorrect format will return a nil value.

var str = "2015-08-26 14:21:40.557"
var dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss.SSS"
var date = dateFormatter.dateFromString(str)

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