简体   繁体   中英

Parsing custom date with NSDateFormatter

I receive from a remote database the following date:

Jan 30 2016 10:32:48:740PM

I want to store it in a NSDate object for other date-related usage.

I used the following code to parse it and convert it to NSdate:

let dateFormatter = NSDateFormatter()
dateFormatter.locale = NSLocale(localeIdentifier: "en_US_POSIX")
dateFormatter.timeZone = NSTimeZone(name: "Asia/Riyadh")
dateFormatter.dateFormat = "M dd yyyy HH:mm:ssz"

let date = dateFormatter.dateFromString("Jan 30 2016 10:32:48:740PM")

print(date)

However, data is always nil !

How can I parse properly?

First of all check this document for date format.

Now, you have month and time format wrong. Change date format as,

dateFormatter.dateFormat = "MMM dd yyyy hh:mm:ss:SSSa"

that should do it.

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