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

标签 swift nsdate nsdateformatter nscalendar

我有一个 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/

相关文章:

ios - 无法使用 UIDocumentPickerViewController 选择 PowerPoint (PPTX) 文档

ios - 如何快速检测用户何时单击 lyft 按钮

ios - 帮助我处理 NSDate 格式

ios - 检查日期是否在下个月

ios - 如何在 iOS 8.1 中转换 "Tue, 14 Jul 2015 15:00:00 +0000"

iphone - 根据时区创建 NSDate 对象

ios - 如何在iOS中生成类似通知的时间字符串?

Swift CGRectMake 中心按钮

SwiftUI macOS - 创建可点击的超链接

iphone - 我如何使用 NSDate 获取下一个日期?