8

I'm trying to use a DateComponentsFormatter to format a number of seconds into a time string HH:MM:SS. I always want to show the minutes and seconds fields but I don't want to show hours if hours is 0. I tried setting

formatter.zeroFormattingBehavior = .dropLeading

But, this causes the minutes to be dropped as well if both hours and minutes are 0.

Currently, my solution is as follows:

if timeElapsed >= 3600 {
    formatter.allowedUnits = [.second, .minute, .hour]
} else {
    formatter.allowedUnits = [.second, .minute]
}
formatter.zeroFormattingBehavior = .pad

However, I'm concerned that this solution is very hacky and won't work correctly if there is some internationalization that doesn't consider one hour to be 3600 seconds. Is there a better solution?

kmell96
  • 1,365
  • 1
  • 15
  • 39
  • 3
    Your `if` sounds reasonable, why would you call it hacky? An hour is a standard unit of measure, like a meter. – Cristik Mar 30 '18 at 22:36
  • 1
    An hour always has 60 minutes. It's the *day* that sometimes has 23 or 25 hours (i.e. on clock change days for countries that use daylight saving time). Your solution looks OK to me. **Disclaimer:** there's also the [leap second](https://www.timeanddate.com/time/leapseconds.html) if you want to go to the atomic clock level. But it's safe to ignore under most circumstances. – Code Different Mar 31 '18 at 00:57

0 Answers0