gpt4 book ai didi

ios - 在 Swift 中分别显示日期和时间

转载 作者:行者123 更新时间:2023-11-28 06:08:54 25 4
gpt4 key购买 nike

尝试在 Swift 3 中分别显示时间和日期,但两个字段均返回 nil。我收到的日期是标准 Date() 格式的字符串。

public func formatDateForAbandonTicket(_ dte: String) -> String {
print(dte)
let timeFormatter = DateFormatter()
timeFormatter.dateFormat = "HH:mm"
let t = timeFormatter.date(from: dte)
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "d/MM/YYYY"
dateFormatter.timeZone = TimeZone(abbreviation: "GMT+0:00")
let d = dateFormatter.date(from: dte)
print()
print(t)
print()
print(d)
return "\(d)" + " " + "\(t)"
}

我从 d 和 t 都得到了零响应。该参数确实包含正确的日期“2017-11-14 16:36:29 +0000”。

谢谢

最佳答案

您的代码不起作用,因为您需要先将 dte 转换为 Date,为此,您需要指定与完整日期字符串相匹配的格式.您只需要一个 Date,而不是两个。

并且没有理由创建两个单独的字符串只是为了将它们组合回一个。

public func formatDateForAbandonTicket(_ dte: String) -> String {
print(dte)
let df = DateFormatter()
df.dateFormat = "yyyy-MM-dd HH:mm:ss Z"
df.locale = Locale(identifier: "en_US_POSIX")
if let date = df.date(from: dte) {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "d/MM/yyyy HH:mm"
dateFormatter.timeZone = TimeZone(secondsFromGMT: 0)
let dateStr = dateFormatter.string(from: date)
return dateStr
} else {
return ""
}
}

另请注意,您正在将结果转换为 UTC 时间而不是用户的区域设置时间。如果这是您的需要,那很好,只要确保它对用户有意义即可。

关于ios - 在 Swift 中分别显示日期和时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47290943/

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