gpt4 book ai didi

ios - 如何显示与当前日期相比的时差?

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

我有一个 createdAt 时间戳。该 createdAt 时间戳将与当前日期 (Date()) 进行比较。

假设当前日期是 2018 年 8 月 1 日。如果创建时间是 2018 年 7 月 28 日,则只显示 2018 年 7 月 28 日。但如果创建时间是同一天(2018 年 8 月 1 日),则只显示 2 米前,5 小时 38 分15 年前,类似这样的事情,比如这个:

enter image description here

我尝试使用下面的代码,但结果不一致。如果日期不同但下面的代码仍然显示 5h 16m。

func calculateTimeDifference() -> String? {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
dateFormatter.locale = Locale(identifier: "en_US_POSIX")

guard let date1 = dateFormatter.date(from: dateTimeString) else {
return nil
}

let date2 = Date()

let components : Set<Calendar.Component> = [.second, .minute, .hour, .day, .month, .year]
let difference = Calendar.current.dateComponents(components, from: date1, to: date2)

var dateTimeDifferenceString = ""

var secondDifference = ""
var minuteDifference = ""
var hourDifference = ""
var dayDifference = ""

if difference.second! < 0 {
secondDifference = "0"
} else {
secondDifference = String(difference.second!)
}

if difference.minute! < 0 {
minuteDifference = "0"
} else {
minuteDifference = String(difference.minute!)
}

if difference.hour! < 0 {
hourDifference = "0"
} else {
hourDifference = String(difference.hour!)
}

if difference.day! < 0 {
dayDifference = "0"
} else{
dayDifference = String(difference.day!)
}


if difference.minute! == 0 {
dateTimeDifferenceString = "\(secondDifference)s"
} else if difference.hour == 0 {
dateTimeDifferenceString = "\(minuteDifference)m"
} else if difference.day == 0 {
dateTimeDifferenceString = "\(hourDifference)h \(minuteDifference)m"
} else if difference.day! > 0 {
dateTimeDifferenceString = "different day \(dayDifference)"
}

return dateTimeDifferenceString
}

能否请您分享您的代码?

最佳答案

就我个人而言,我会使用 DateComponentsFormatter,这是比尝试按时执行数学运算更安全的选择,这绝不是一个好主意

let duration = Date().timeIntervalSince(date1)
let formatter = DateComponentsFormatter()
formatter.unitsStyle = .abbreviated
formatter.allowedUnits = [ .day, .hour, .minute, .second]

let durationFormat = formatter.string(from: duration)

看看Formatting a Duration with NSDateComponentsFormatter了解更多详情。

关于ios - 如何显示与当前日期相比的时差?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51624644/

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