0
let dateFormatter = DateFormatter()
dateFormatter.dateStyle = .short
dateFormatter.timeStyle = .none
let date = dateFormatter.date(from: "Sep 1, 1906")

Sep 1, 1906 always return nil in America/Edmonton timezone and Apr 4, 1986 for Jordan/Amman.

Does anyone know why? what am I doing wrong?

Steve Mclean
  • 149
  • 1
  • 12
  • 2
    It fails because there was no "00:00" time in Edmonton on Sep 1, 1906, or in Jordan on Apr 4, 1986. On these days the clock was adjusted forward. – Martin R Sep 01 '18 at 19:07
  • 1
    you just need to set DateFormatter calendar property to any value other than nil `dateFormatter.calendar = .current` https://stackoverflow.com/a/32408916/2303865 – Leo Dabus Sep 01 '18 at 19:28
  • @MartinR great, setting lenient property to true worked, I don't understand completely how this made it work and I am wondering whether it has any side effect - Thank you Martin :) – Steve Mclean Sep 01 '18 at 19:34
  • 1
    @LeoDabus your solution worked too. But I don't understand why - Thank you Leo – Steve Mclean Sep 01 '18 at 19:36
  • @AbedAlansari you are welcome. – Leo Dabus Sep 01 '18 at 19:40
  • 1
    Alberta (where Edmonton is) adopted MST on Sep 1, 1906. So, local time in Edmonton on Sep 1, 1906 starts on "00:33:52". Apr 4, 1986 is the DST changing date in Jordan, local time starts "01:00:00". `DateFormatter` assumes "00:00:00" for time when only date part is given, so it may return nil on such specific dates. With setting `isLenient`, `DateFormatter` guesses such missing time. – OOPer Sep 01 '18 at 19:40

0 Answers0