Swift 根据时间戳显示时间或日期 [英] Swift displaying the time or date based on timestamp

查看:102
本文介绍了Swift 根据时间戳显示时间或日期的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 API 可以返回数据,包括该记录的时间戳.在 swift 中,我加载了时间戳元素并将其转换为双精度值,然后可以将其转换为时间.如果记录的日期是今天,我希望能够返回时间,如果记录不是今天,则返回日期.见下图:

I have an API that returns data including a timestamp for that record. In swift I have the timestamp element loaded and converted into a double and can then convert that into time. I want to be able to return the time if the date of the record is today and return the date if the record is not today. See below:

        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 来查看日期"是否为今天,然后执行某些操作?那么您如何本地化时间以使其对用户而不是服务器时间正确?

Do I use NSCalendar to see if 'date' is today and then do something? How do you then localise the time so that its correct for the user rather than server time?

推荐答案

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

There is a handy function on NSCalendar that tells you whether an NSDate is in today or not (requires at least iOS 8) isDateInToday()

要查看它是否有效,请将其放入操场:

To see it working, put this into a 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)

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

Or, if you just want to see what it looks like without running it yourself:

这篇关于Swift 根据时间戳显示时间或日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆