gpt4 book ai didi

ios - DateComponentsFormatter 返回错误的单位计数

转载 作者:技术小花猫 更新时间:2023-10-29 10:39:03 27 4
gpt4 key购买 nike

DateComponentsFormatter 返回意外数量的单位时,我遇到了问题。有没有人遇到同样的问题?

import Foundation

let formatter = DateComponentsFormatter()
formatter.unitsStyle = .full;
formatter.maximumUnitCount = 1;

let date = Date(timeIntervalSinceNow: -14.7 * 24 * 60 * 60)
let dateString = formatter.string(from: date, to: Date()) // 2 weeks 1 day

我希望收到“2 周”,但只有“2 周 1 天”。

最佳答案

我通过检查逗号分隔符并使用它来对 DateFormatters 输出进​​行子字符串化解决了这个问题,Swift 3 中的 PlayGround 示例

// Test date
var df = DateFormatter()
df.dateFormat = "dd.MM.yyyy HH:mm:ss"
df.timeZone = TimeZone(secondsFromGMT: 0)
let fromDate = df.date(from: "01.01.2000 00:00:00")
var timeDifference = Date().timeIntervalSince(fromDate!)

// Setup formatter
let formatter = DateComponentsFormatter()
formatter.unitsStyle = .full
formatter.includesApproximationPhrase = false
formatter.zeroFormattingBehavior = .dropAll
formatter.maximumUnitCount = 1
formatter.allowsFractionalUnits = false

// Use the configured formatter to generate the string.
var outputString = formatter.string(from: timeDifference) ?? ""

// Remove 2nd unit if exists
let commaIndex = outputString.characters.index(of: ",") ?? outputString.endIndex
outputString = outputString.substring(to: commaIndex)

// Result
print(outputString)

关于ios - DateComponentsFormatter 返回错误的单位计数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41186170/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com