Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save longvudai/aabc8a13a9844c5551e829939a6f97d6 to your computer and use it in GitHub Desktop.
Save longvudai/aabc8a13a9844c5551e829939a6f97d6 to your computer and use it in GitHub Desktop.
DateComponentsFormatter Playground
import UIKit
/*:
DateComponentsFormatter: A formatter that creates string representations of quantities of time.
*/
let dateComponentsFormatter = DateComponentsFormatter()
/*:
A DateComponentsFormatter can be configured with an array of NSCalendarUnits. These components are then used in the output.
*/
dateComponentsFormatter.allowedUnits = [.hour, .minute, .second]
/*:
A DateComponentsFormatter can be given a units style, which dictates how the units are output:
.abbreviated - 1h 10m
.brief - 1hr 10min (iOS 10+)
.full - 1 hour, 10 minutes
.positional - 1:10
.short - 1 hr 10 min
.spellout - one hour, ten minutes
*/
dateComponentsFormatter.unitsStyle = .short
/*:
Zero formatting behaviour can be specified. This is a bitmask, so multiple values can be provided:
.dropLeading - Off: "0h 10m", On: "10m"
.dropMiddle - Off: "1h 0m 10s", On: "1h 10s"
.dropTrailing - Off: "1h 0m", On: "1h"
.dropAll -
.pad - Off: "1:0:10", On: "01:00:10"
*/
dateComponentsFormatter.zeroFormattingBehavior = [.dropLeading, .dropTrailing]
/*:
Fractional units can be toggled. This would allow 1h30m to be returned as 1.5h
*/
dateComponentsFormatter.allowsFractionalUnits = false //Default
/*:
The maximum unit count can be controlled.
When set, this number dictates the number of units, from greatest to smallest, to represent.
The default is 0, which is interpreted as unlimited.
*/
dateComponentsFormatter.maximumUnitCount = 3
/*:
The largest unit can be collapsed.
This would allow 1m 3s to be displayed as 63s
*/
dateComponentsFormatter.collapsesLargestUnit = true
/*:
An approximation phrase can be added to any output strings if you deem the configuration to yield inaccurate results.
1h 10m becomes about 1h 10m
Languages where this would produce incorrect results are handled
*/
dateComponentsFormatter.includesApproximationPhrase = true
/*:
A time remaining phrase can also be added.
1h 10m becomes 1h 10m remaining
*/
dateComponentsFormatter.includesTimeRemainingPhrase = true
/*:
A string can be generated for a given TimeInterval
*/
print(dateComponentsFormatter.string(from: 32000)!)
/*:
A string can also be generated for the interval between two dates
*/
let startDate = Date(timeIntervalSince1970: 154000)
let endDate = Date()
print(dateComponentsFormatter.string(from: startDate, to: endDate)!)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment