-3

I have a valid Date() object I am trying to convert. I've looked at other SO posts and it seems like my code should do it:

private func getHoursMinutesString(date:Date)  -> String
{
    let formatter = Foundation.DateFormatter()
    formatter.dateFormat = "HH:mm"
    return formatter.string(from: date)
}

However, the time returned is always "00:00". If a put a fresh Date() object in, it will return the right time. I'm wondering what might be wrong with my Date() object that you could see? Here is an lldb printout of the data:

date formatter issue

As you can see, the formatter is a valid object. The date (I think) is a valid date object. When passed through the formatter it becomes "00:00" but it works fine with a new Date() object.

Is there anything in the date object that stands out as improperly formatted or missing? Or is there an extra step I am missing in my formatter?

Update After doing research, setting a timezone fixes the problem. Why, I don't know!

rmaddy
  • 314,917
  • 42
  • 532
  • 579
Aggressor
  • 13,323
  • 24
  • 103
  • 182
  • Your output is correct assuming you live 5 hours from UTC. `date` is midnight in your local time. – rmaddy Nov 24 '17 at 17:44
  • Hmm ah ok. It seemed weird because I was seeing 05:00 and I was expecting to get 05:00 from the time stamp. – Aggressor Nov 24 '17 at 17:47
  • 1
    It's 5am UTC time (the +0000 means UTC). DateFormatter, by default, shows you a value in local time. – rmaddy Nov 24 '17 at 17:47

1 Answers1

0

try add this:

dateFormatter.timeZone = NSTimeZone(name: "UTC")
Kevinosaurio
  • 1,952
  • 2
  • 15
  • 18
  • There is no need for this. – rmaddy Nov 24 '17 at 17:44
  • 2
    And if you wanted to do this (e.g. building some string for internal storage and thereby wanting to use GMT/UTC/Zulu), I'd use `TimeZone`, not `NSTimeZone`. E.g. `formatter.timeZone = TimeZone(secondsFromGMT: 0)`. – Rob Nov 24 '17 at 18:18