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