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

rmaddy
  • 314,917
  • 42
  • 532
  • 579
Ackman
  • 1,562
  • 6
  • 31
  • 54
  • 1
    `DateFormatter` assumes local time unless told otherwise. So seeing 17:00:00 UTC makes perfect sense assuming you live in EST (UTC -5). – rmaddy Dec 06 '17 at 20:15

2 Answers2

2

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

Martin R
  • 529,903
  • 94
  • 1,240
  • 1,382
  • 2017-10-24 17:00:00 +0000 I am still getting incorrect time stamp – Ackman Dec 06 '17 at 20:21
  • @Ackman: Note that a Date has no timezone and is always printed in GMT. "12:00 PM" in your time zone is 17:00 in the GMT timezone, so the result is correct. See also https://stackoverflow.com/questions/39937019/nsdate-or-date-shows-the-wrong-time. – Martin R Dec 06 '17 at 20:23
0

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!)
ByteSlinger
  • 1,439
  • 1
  • 17
  • 28
  • 10/24 12:00 PM ----->Deliveryby 2017-10-24 17:00:56 +0000----->dateCompleted why is there a time difference? – Ackman Dec 06 '17 at 20:24