Henry Ngan Henry Ngan - 9 months ago 21
Swift Question

How to display date with human language like "Today at xx:xx pm", "Yesterday at xx:xx am"?

I have a date "2014-07-02 20:57:38 +0000" and I want to format it as "Today at 8:57 pm".
I want that if a string is yesterday, then display it as "Yesterday at 9:00 am". If it is neither today or yesterday, just show the actually date like "27/6 at 7:53 pm".

I was able to get the time with format like "8:57 AM" with the code below.

var formatter : NSDateFormatter = NSDateFormatter()
formatter.dateFormat = "h:mm a"

// message.createdAt is the date
let dateString = formatter.stringFromDate(message.createdAt)
println(dateString)

//output = 8:57 AM


However, when I use the following code, it returns a blank string.

var formatter : NSDateFormatter = NSDateFormatter()
formatter.dateFormat = "h:mm a"
formatter.doesRelativeDateFormatting = true //<-- This doesn't work

let dateString = formatter.stringFromDate(message.createdAt)
println(dateString)

//output = (nothing, its a blank string)


How do I make this work and display "Today" or "Yesterday" in Swift?

Answer Source

The reason it's blank is that your date format only has time components. Combined with .doesRelativeDateFormatting that gives you the empty string. If you want that custom time format, I think you need separate formatters for the date and the time:

let now = NSDate()

let dateFormatter = NSDateFormatter()
dateFormatter.dateStyle = .MediumStyle
dateFormatter.doesRelativeDateFormatting = true

let timeFormatter = NSDateFormatter()
timeFormatter.dateFormat = "h:mm a"

let time = "\(dateFormatter.stringFromDate(now)), \(timeFormatter.stringFromDate(now))"
println(time)      // prints "Today, 5:10 PM"