Mathew Jenkinson Mathew Jenkinson - 1 year ago 87
Swift Question

Swift displaying the time or date based on timestamp

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)

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?

Answer Source

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.

// This should just show the date.

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

enter image description here