Ben Ben - 1 month ago 10x
iOS Question

Swift - check if a timestamp is yesterday, today, tomorrow, or X days ago

I'm trying to work out how to decide if a given timestamp occurs today, or +1 / -1 days. Essentially, I'd like to do something like this (Pseudocode)

IF days_from_today(timestamp) == -1 RETURN 'Yesterday'
ELSE IF days_from_today(timestamp) == 0 RETURN 'Today'
ELSE IF days_from_today(timestamp) == 1 RETURN 'Tomorrow'
ELSE IF days_from_today(timestamp) < 1 RETURN days_from_today(timestamp) + ' days ago'
ELSE RETURN 'In ' + days_from_today(timestamp) + ' ago'

Crucially though, it needs to be in Swift and I'm struggling with the NSDate / NSCalendar objects. I started with working out the time difference like this:

let calendar = NSCalendar.currentCalendar()
let date = NSDate(timeIntervalSince1970: Double(timestamp))
let timeDifference = calendar.components([.Second,.Minute,.Day,.Hour],
fromDate: date, toDate: NSDate(), options: NSCalendarOptions())

However comparing in this way isn't easy, because the
is different depending on the time of day and the timestamp. In PHP I'd just use mktime to create a new date, based on the start of the day (i.e.
), but I'm not sure of the easiest way to do that in Swift.

Does anybody have a good idea on how to approach this? Perhaps an extension to NSDate or something similar would be best?


NSCalendar has methods for all three cases

func isDateInYesterday(_ date: NSDate) -> Bool
func isDateInToday(_ date: NSDate) -> Bool
func isDateInTomorrow(_ date: NSDate) -> Bool

To calculate the days earlier than yesterday use

func components(_ unitFlags: NSCalendarUnit,
      fromDate startingDate: NSDate,
          toDate resultDate: NSDate,
               options opts: NSCalendarOptions) -> NSDateComponents

pass .Day to unitFlags and get the day property from the result.


This is a function which considers also is in for earlier and later dates by stripping the time part.

func dayDifferenceFromDate(timestamp : Int) -> String
  let calendar = NSCalendar.currentCalendar()
  let date = NSDate(timeIntervalSince1970: Double(timestamp))
  if calendar.isDateInYesterday(date) { return "Yesterday" }
  else if calendar.isDateInToday(date) { return "Today" }
  else if calendar.isDateInTomorrow(date) { return "Tomorrow" }
  else {
    let startOfNow = calendar.startOfDayForDate(NSDate())
    let startOfTimeStamp = calendar.startOfDayForDate(date)
    let components = calendar.components(.Day, fromDate: startOfNow, toDate: startOfTimeStamp, options: [])
    let day =
    if day < 1 { return "\(abs(day)) days ago" }
    else { return "In \(day) days" }