gpt4 book ai didi

Swift 根据时间戳显示时间或日期

转载 作者:搜寻专家 更新时间:2023-11-01 05:56:57 24 4
gpt4 key购买 nike

我有一个 API 可以返回包含该记录的时间戳的数据。在 swift 中,我加载了时间戳元素并将其转换为 double ,然后可以将其转换为时间。如果记录的日期是今天,我希望能够返回时间;如果记录不是今天,我希望能够返回日期。见下文:

        let unixTimeString:Double = Double(rowData["Timestamp"] as! String)!
let date = NSDate(timeIntervalSince1970: unixTimeString) // This is on EST time and has not yet been localised.
var dateFormatter = NSDateFormatter()
dateFormatter.timeStyle = .ShortStyle
dateFormatter.doesRelativeDateFormatting = true
// If the date is today then just display the time, if the date is not today display the date and change the text color to grey.
var stringTimestampResponse = dateFormatter.stringFromDate(date)
cell.timestampLabel.text = String(stringTimestampResponse)

我是否使用 NSCalendar 来查看“日期”是否为今天,然后再做些什么?然后,您如何本地化时间,使其对用户而不是服务器时间正确?

最佳答案

NSCalendar 上有一个方便的函数可以告诉您 NSDate 是否在今天(至少需要 iOS 8)isDateInToday()

要查看它是否正常工作,请将它放到 playground 中:

// Create a couple of unix dates.
let timeIntervalToday: NSTimeInterval = NSDate().timeIntervalSince1970
let timeIntervalLastYear: NSTimeInterval = 1438435830


// This is just to show what the dates are.
let now = NSDate(timeIntervalSince1970: timeIntervalToday)
let then = NSDate(timeIntervalSince1970: timeIntervalLastYear)

// This is the function to show a formatted date from the timestamp
func displayTimestamp(ts: Double) -> String {
let date = NSDate(timeIntervalSince1970: ts)
let formatter = NSDateFormatter()
formatter.timeZone = NSTimeZone.systemTimeZone()

if NSCalendar.currentCalendar().isDateInToday(date) {
formatter.dateStyle = .NoStyle
formatter.timeStyle = .ShortStyle
} else {
formatter.dateStyle = .ShortStyle
formatter.timeStyle = .NoStyle
}

return formatter.stringFromDate(date)
}

// This should just show the time.
displayTimestamp(timeIntervalToday)

// This should just show the date.
displayTimestamp(timeIntervalLastYear)

或者,如果您只是想看看它是什么样子而不自己运行它:

enter image description here

关于Swift 根据时间戳显示时间或日期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38701071/

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