Search code examples
swiftnsdateformatter

incorrect string to date conversion swift 3.0


I am converting a format like 10/24 12:00 PM in string to the equivalent in Date format. I am using the following code:

let dateFormatter = DateFormatter()
    dateFormatter.dateFormat = "MM/dd hh:mm aa"

   self.dateCompleted = dateFormatter.date(from: self.DeliverBy!)

dateCompleted is a Date variable whereas self.DeliveryBy is a String variable.

I am getting an output like 2000-10-24 17:00:00 UTC where as it should be something like 2017-10-24 12:00:00 UTC. Am i doing something wrong?

I referred http://userguide.icu-project.org/formatparse/datetime


Solution

  • Your date string does not specify a year, which is therefore determined from the default date. What you can do is to set the default date to the (start of the) current day:

    let dateFormatter = DateFormatter()
    dateFormatter.dateFormat = "MM/dd hh:mm aa"
    dateFormatter.defaultDate = Calendar.current.startOfDay(for: Date())
    if let dateCompleted = dateFormatter.date(from: "10/24 12:00 PM") {
        print(dateCompleted) // 2017-10-24 10:00:00 +0000
    }
    

    (I am in the Europe/Berlin timezone, therefore 12:00 PM is printed as 10:00 GMT.)