DateComponentsFormatter drop zero hours but not zero minutes

自作多情 提交于 2019-12-12 12:44:04

问题


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?

来源:https://stackoverflow.com/questions/49581717/datecomponentsformatter-drop-zero-hours-but-not-zero-minutes

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!