Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert a string UTC date to NSDate in Swift

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")
like image 282
jonv562 Avatar asked Nov 02 '15 18:11

jonv562


People also ask

How do I convert a string to a date in Swift?

The class we use to convert a string to a date in Swift is DateFormatter (or NSDateFormatter if you are using Objective-C).

How do you convert UTC to local time in Swift?

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.

What is date UTC format?

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.


3 Answers

I think this should work

let formatter = DateFormatter()
formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZ"
let localDate = formatter.date(from: date)
like image 65
ozzyzig Avatar answered Dec 25 '22 04:12

ozzyzig


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!)
like image 44
BHUVANESH MOHANKUMAR Avatar answered Dec 25 '22 04:12

BHUVANESH MOHANKUMAR


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

like image 38
Artemiy Shlesberg Avatar answered Dec 25 '22 02:12

Artemiy Shlesberg