【问题标题】:Using Years unit interval in Swift Foundation Measurements framework在 Swift Foundation Measurements 框架中使用年单位间隔
【发布时间】:2019-11-01 01:27:41
【问题描述】:

如何使用 Foundation 的 Measurements() 以年(或年 + 月)显示日期迭代?我已经让它显示间隔,但我发现它是小时的最大单位……它对我无效(以漂亮的本地化显示 87600 小时,间隔 10 年)

如何解决这个问题?

我的代码:

// 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)
}

【问题讨论】:

  • 测量不是您显示时间间隔的方式。
  • 那么它是什么单位持续时间其他像时间间隔?来自文档: Duration Duration 是一个时间量。时间的 SI 单位是秒 (sec),它是根据铯 133 原子的放射性定义的。持续时间通常也以分钟 (min) 和小时 (hr) 表示。年/月/日只是另一个时间间隔表达式
  • 它还在文档中说要使用 DateComponents 年、月、周和日。
  • 我在寻找解决方案而不是争论。

标签: swift xcode foundation units-of-measurement measurement


【解决方案1】:

如何使用 Foundation 的 Measurements 以年(或年 + 月)显示日期迭代

你没有。你使用DateComponentsFormatter

【讨论】:

  • 感谢@matt 成功了。对于是否使用 Measurements 或 DateComponents 来获得正确的本地化字符串,我很抱歉。现在它在您的帮助下完美运行
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-09-21
  • 1970-01-01
相关资源
最近更新 更多