简体   繁体   中英

SWIFT : Convert String from XLM to NSDate

The following code works on the simulator but doesn't on devices. I tried to replace Z with xx with no luck. Any help appreciated.

Thanks.

func convertDateStringToNSDate(dateString: String) -> NSDate {
        var dateFormatter = NSDateFormatter()
        // Sat, 20 Jun 2015 16:50:20 +0200

         dateFormatter.dateFormat = "EEE, dd MMM yyyy HH:mm:ss xx"
         let date: NSDate = dateFormatter.dateFromString(dateString)
         return date

    }

If you're working with fixed-format dates, you should first set the locale of the date formatter to something appropriate for your fixed format. In most cases the best locale to choose is en_US_POSIX, a locale that's specifically designed to yield US English results regardless of both user and system preferences. en_US_POSIX is also invariant in time (if the US, at some point in the future, changes the way it formats dates, en_US will change to reflect the new behavior, but en_US_POSIX will not), and between platforms (en_US_POSIX works the same on iPhone OS as it does on OS X, and as it does on other platforms).

// Setting the locale to POSIX ensures that
// the user's locale won't be used
dateFormatter.locale = NSLocale(localeIdentifier: "en_US_POSIX")

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