incorrect string to date conversion swift 3.0

2019-08-25 03:24发布

问题:

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

回答1:

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



回答2:

You can load the current date info into the DateFormatter:

let dateFormatter = DateFormatter()

dateFormatter.dateFormat = "MM/dd hh:mm aa"

dateFormatter.defaultDate = Date() // start with the current date

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