Swift displaying the time or date based on timestamp

若如初见. 提交于 2019-12-06 16:43:39

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:

Abizern's answer in Swift 3:

import UIKit
let timeIntervalToday: TimeInterval = Date().timeIntervalSince1970
let timeIntervalLastYear: TimeInterval = 1438435830

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

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

    if Calendar.current.isDateInToday(date) {
        formatter.dateStyle = .none
        formatter.timeStyle = .short
    } else {
        formatter.dateStyle = .short
        formatter.timeStyle = .none
    }

    return formatter.string(from: date)
}

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

// This should just show the date.
displayTimestamp(ts: timeIntervalLastYear)
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!