0

I try to get a date but I only have a time available. For now, I don't care about year, month or day. All that matters is the time.

My input is in the form "hh:mm:ss" (i.e. European time format).

The problem is that any time above 12:59:59 does not work !

How can I get dates from times above 12:59:59 ????

My code looks like follows:

import UIKit

let str = "17:02:09"

let mydateFormatter = DateFormatter()
mydateFormatter.dateFormat = "hh:mm:ss"
let timezone = TimeZone(abbreviation: "CEST") ?? TimeZone.current
mydateFormatter.timeZone = timezone
mydateFormatter.locale = Locale(identifier: "de_DE") as Locale?

let date1 = mydateFormatter.date(from: str)

print(date1?.description ?? "no date available")

Output: no date available

If I set the str's hour setting to anything below or equal to 12, then it works.

For example, if I set str = "12:02:09", I get the output: 1999-12-31 23:02:09 +0000

For example, if I set str = "10:02:09, I get the output: 2000-01-01 09:02:09 +0000

For example, if I set str = "13:02:09, I get the output: no date available

How can I get dates from times above 12:59:59 ????

And ideally, how can I get dates that have a matching time with the input-time ?

iKK
  • 6,394
  • 10
  • 58
  • 131
  • 4
    change your date formatter to "HH:mm:ss". hh is for 01-12 hours (usually used for am/pm time) HH is for 24h time 00-23 hours – Leo Dabus Dec 30 '18 at 13:03
  • When you print the date description it will always show UTC time – Leo Dabus Dec 30 '18 at 13:04
  • wow - that simple !! Thank you very much. I did not realise that there is another string-format for hours. – iKK Dec 30 '18 at 13:05
  • Ah, and for matching time (i.e. same as input-time) I cannot really use `description` since it is in UTC always. I guess I can use the same DateFormatter I already have for is, such as `print(mydateFormatter.string(from: date1 ?? Date()))` – iKK Dec 30 '18 at 13:09
  • Yes. Note that when displaying dates to the user you shouldn't use a custom dateFormat. Just use the `dateStyle` and `timeStyle` (short/medium/long/full) so it shows the date respecting the user's locale/settings. – Leo Dabus Dec 30 '18 at 13:11
  • 1
    Btw if you need today's date with the time inputed, you can set the date formatter `defaultDate` to today's date `Date()`. And if you want to zero out the seconds/milliseconds of the date you can use `mydateFormatter.defaultDate = Calendar.current.startOfDay(for: Date())` – Leo Dabus Dec 30 '18 at 13:20
  • 1
    Thank you very much, Leo. This is all very helpful ! – iKK Dec 30 '18 at 13:23
  • You might be interest in this one also https://stackoverflow.com/a/28347285/2303865 – Leo Dabus Dec 30 '18 at 13:35

0 Answers0