Search code examples
swiftxcodefoundationunits-of-measurementmeasurement

Using Years unit interval in Swift Foundation Measurements framework


how can I display date iterval in years (or years + months) using Foundation’s Measurements()? I’ve made it to display interval but biggest unit I’ve found it hours … and it is not valid for me (display with beautiful localisation 87600 hours for 10y interval)

how to fix this?

my code:

// MODEL part
var yearsLived: Measurement<UnitDuration>? {
    if let hours = birthDate?.getInterval(toDate: deathDate, component: .hour) {
        let hours = Measurement(value: Double(hours), unit: UnitDuration.hours)
        return hours
    }
    return nil
}

// VC PART:
if let yearsLived = person?.yearsLived {
    let formatter = MeasurementFormatter()
    formatter.unitStyle = .long
    formatter.unitOptions = [.naturalScale]

    yearsLivedLabel.text = formatter.string(from: yearsLived)
}

Solution

  • how can I display date iterval in years (or years + months) using Foundation’s Measurements

    You don't. You use DateComponentsFormatter.