5

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.

mfaani
  • 33,269
  • 19
  • 164
  • 293
Gagan_iOS
  • 3,638
  • 3
  • 32
  • 51

1 Answers1

5

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".

rmaddy
  • 314,917
  • 42
  • 532
  • 579
Krunal
  • 77,632
  • 48
  • 245
  • 261
  • 3
    this is still wrong. You need to set the date formatter locale to "en_US_POSIX" when parsing fixed date formats – Leo Dabus May 29 '18 at 14:45
  • thanks, Krunal & Martin.. You saved my another 2 hours on the same issue. – Gagan_iOS May 29 '18 at 14:51
  • 2
    A suggestion - 1. No need for two complete sections to the answer. Just post one complete solution. 2. Since none of your answer was actually written by you (since you credit two people for providing all of the solutions), consider making this answer community wiki. – rmaddy May 29 '18 at 15:09
  • 1
    @Krunal Go to https://www.unicode.org/reports/tr35/tr35-dates.html#Date_Format_Patterns and see what `s`, `S`, and `z` represent. – rmaddy May 29 '18 at 15:22