问题
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