I'm getting UTC string dates that look like this "2015-10-17T00:00:00.000Z" and want to convert them to an NSDate in this format "October 12th 2015 11:19:12 am"
This is the route that I'm trying but I can't seem to get the right dateFormat.
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = //can't seem to get this right
dateFormatter.timeZone = NSTimeZone(name: "UTC")
let date = dateFormatter.dateFromString("2015-10-17T00:00:00.000Z")
The class we use to convert a string to a date in Swift is DateFormatter (or NSDateFormatter if you are using Objective-C).
I want to convert server UTC time to local time and vice-versa. Here is my code.. var isTimeFromServer = true var time:String! var period:String! let timeString = "6:59 AM" //Current UTC time if isTimeFromServer { let index = timeString.
UTC() takes comma-delimited date and time parameters and returns the number of milliseconds between January 1, 1970, 00:00:00, universal time and the specified date and time.
I think this should work
let formatter = DateFormatter()
formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZ"
let localDate = formatter.date(from: date)
This works for Swift 3.0 and latest Xcode [April 2017]
let dateString = "2017-Jan-01 12:00:00.250"
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-M-dd HH:mm:ss.SSS"
dateFormatter.locale = Locale.init(identifier: "en_GB")
let dateObj = dateFormatter.date(from: dateString)
let date = dateObj
let formatter = DateFormatter()
formatter.calendar = Calendar(identifier: .iso8601)
formatter.locale = Locale(identifier: "en_US_POSIX")
formatter.timeZone = TimeZone(secondsFromGMT: 0)
formatter.dateFormat = "yyyy-MM-dd HH:mm:ss.SSSXXXXX"
let currentDateTime = formatter.string(from: date!)
Swift 4 code
let dateString = "2015-10-17T00:00:00.000Z"
let formatter = DateFormatter()
formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZ"
let date = formatter.date(from: dateString)
You can find useful info about date formats here
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With