1

I want to convert a string into a date and use a small function. If I run the code the results is different from the input:

 let startDateString = "20-02-2022-15-00"
        print(startDateString)
        let dateFormatter = DateFormatter()
        dateFormatter.dateFormat = "DD-MM-YYYY-HH:mm"
        dateFormatter.timeZone = TimeZone.current
        let startDate = dateFormatter.date(from: startDateString)
        print(startDate!)

the startDateString is "20-02-2022-15-00" the result of startDate is: 2021-12-27 14:00:00 +0000

The results has the wrong format YYYY-MM-DD HH:MM vs DD-MM-YYYY-HH:mm and the date is about two month in the past.

What am I doing wrong?

Shehata Gamal
  • 98,760
  • 8
  • 65
  • 87
Michael
  • 616
  • 5
  • 20

1 Answers1

2

You need yyyy not YYYY

dateFormatter.dateFormat = "dd-MM-yyyy-HH:mm"
Shehata Gamal
  • 98,760
  • 8
  • 65
  • 87