Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Date from Server in Swift

I am facing an issue while converting date string coming from the server in Date. Below is my code

let dateString = "2017–04–02T13:10:00.000"  //Date coming from server
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd'T'hh:mm:ss.SSS"
let date =  dateFormatter.date(from: dateString)
print("date is :\(String(describing: date))")

But log is

date is :nil

*Updated for 24-hour format

Below is the update for 24-hour format(HH)

let dateString = "2017–04–02T13:10:00.000"
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSS"
let date =  dateFormatter.date(from: dateString)

yet same result

I have tried these links

Link1 Link2 Link3 etc

but with no success.

Please let me know what am I doing wrong with above code.

like image 227
Gagan_iOS Avatar asked May 29 '18 14:05

Gagan_iOS


1 Answers

Answer to your question: Do not type hyphen/dash character or symbol from your keyboard. Just copy it from your console window (web service response print statements and paste in your date format)

Try this and see:

let dateString = "2017–04–02T13:10:00.000"  //Date coming from server
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy–MM–dd'T'HH:mm:ss.SSS"
dateFormatter.locale = Locale(identifier: "en_US_POSIX")
let date =  dateFormatter.date(from: dateString)
print("date is :\(String(describing: date))")

Result: date is :Optional(2017-04-02 07:40:00 +0000)

Also note that you have a timezone issue. Your original date string does not provide any specific timezone. So you need to decided what timezone the string represents. Since it is coming from a server it is most likely in UTC time. If so, you need to set the timeZone property of the date formatter. Otherwise the string will be parsed as if it were user local time.

dateFormatter.timeZone = TimeZone(secondsFromGMT: 0)

Credit: Martin R
The server string contains "EN-DASH" (U+2013) as separators, not normal hyphens (minus signs).

(As suggested by Leo Dabus), set locale identifier for your date formatter - "en_US_POSIX".

like image 122
5 revs, 2 users 70% Avatar answered Sep 30 '22 13:09

5 revs, 2 users 70%