Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I convert including timezone date in swift?

I want to convert 2015-08-14T20:02:25-04:00 to 2015-08-14 16:02
I tried below, but it could't execute well(returned nil).

let d = "2015-08-14T20:02:25-04:00" let formatter = NSDateFormatter() formatter.dateFormat = "yyyy-MM-dd HH:mm:ss ZZZZ" let date: NSDate? = formatter.dateFromString(d) 

How can I convert this date format?

like image 778
naohide_a Avatar asked Aug 15 '15 08:08

naohide_a


People also ask

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.

How do I change the current timeZone in Swift?

Standard Approach, using a DateFormatter() đŸ—“current timeZone. This will be set to . current by default, but it is important to note in case you need to set anything other that the current timeZone that you exist in.


2 Answers

Xcode 8 • Swift 3

You need to escape 'T' and use the appropriate timezone symbol. Note that it will depend if your date string represents a UTC (zero seconds from GMT) time timezone with Z "XXXXX" or without it +00:00 "xxxxx":

let dateString = "2015-08-14T20:02:25-04:00" let formatter = DateFormatter() formatter.locale = Locale(identifier: "en_US_POSIX") formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssXXXXX" if let date = formatter.date(from: dateString) {     formatter.dateFormat = "yyyy-MM-dd HH:mm"     let string = formatter.string(from: date)     print(string) } 

If you need some reference you can use this:

enter image description here

like image 155
Leo Dabus Avatar answered Sep 21 '22 13:09

Leo Dabus


You can use :

formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZZZ" 

Hope this help you !

like image 35
Joffrey Outtier Avatar answered Sep 19 '22 13:09

Joffrey Outtier