-1

Why does DateFormatter return nil? I think the string format matches?

let dateString = ("01/05/2017")!
let dateFormatter = DateFormatter()
dateFormatter.timeZone = TimeZone.current
dateFormatter.dateFormat = "dd/MMM/yyyy"
let dateObj = dateFormatter.date(from: dateString)

After executing the code above, the dateObj is nil.

Hamish
  • 78,605
  • 19
  • 187
  • 280
Teun Vos
  • 69
  • 7
  • 1
    That simply means that the string does not match the date format. – Apple provides a [Data Formatting Guide](https://developer.apple.com/library/content/documentation/Cocoa/Conceptual/DataFormatting/Articles/dfDateFormatting10_4.html#//apple_ref/doc/uid/TP40002369-SW1) which links to the [Date Format Patterns](http://www.unicode.org/reports/tr35/tr35-31/tr35-dates.html#Date_Format_Patterns) documentation. – Martin R Jun 02 '17 at 12:15
  • 2
    `let dateString = ("01/05/2017")!` looks so ugly. What are you trying to unwrap there? There is no optional value in a regular string. – Leo Dabus Jun 02 '17 at 12:17
  • change your String from `let dateString = ("01/05/2017")!` to let dateString = "01/05/2017" – Anbu.Karthik Jun 02 '17 at 12:18
  • Well, this is embarassing. I just had a typo in my code. Thanks for all the help :) – Teun Vos Jun 02 '17 at 15:27

4 Answers4

1

For month you need to use MM because MMM is used when you having month in the format like Jan,Feb,Mar and so on. So your dateFormat should be dd/MM/yyyy.

let dateString = "01/05/2017"
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "dd/MM/yyyy"
let dateObj = dateFormatter.date(from: dateString)

Note: No need to set timeZone to TimeZone.current

Nirav D
  • 71,513
  • 12
  • 161
  • 183
0

Replace with your dateFormat:

dateFormatter.dateFormat = "dd/MM/yyyy"
KKRocks
  • 8,222
  • 1
  • 18
  • 84
0

date Formatter should be dateFormatter.dateFormat = "dd/MM/yyyy" in this case.

SuryaKantSharma
  • 1,113
  • 12
  • 27
0

You can check various date format from given link

NSDateFormatter

For given example you can use let formaterStrig = "dd/MM/yyyy"

ERbittuu
  • 968
  • 8
  • 19