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

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


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 = .MediumStyledateFormatter.doesRelativeDateFormatting = truelet timeFormatter = NSDateFormatter()timeFormatter.dateFormat = "h:mm a"let time = "\(dateFormatter.stringFromDate(now)), \(timeFormatter.stringFromDate(now))"println(time)      // prints "Today, 5:10 PM"


With Swift 5.1, Apple Developer API Reference states about DateFormatter's dateFormat property:

You should only set this property when working with fixed format representations, as discussed in Working With Fixed Format Date Representations. For user-visible representations, you should use the dateStyle and timeStyle properties, or the setLocalizedDateFormatFromTemplate(_:) method if your desired format cannot be achieved using the predefined styles; both of these properties and this method provide a localized date representation appropriate for display to the user.


The following Playground sample code shows how to display your dates in the desired format using dateStyle, timeStyle and doesRelativeDateFormatting properties:

import Foundationlet now = Date() // 2019-08-09 12:25:12 +0000let yesterday = Calendar.current.date(byAdding: .day, value: -1, to: now)! // 2019-08-08 12:25:12 +0000let aWeekAgo = Calendar.current.date(byAdding: .weekOfMonth, value: -1, to: now)! // 2019-08-02 12:25:12 +0000let dateFormatter = DateFormatter()dateFormatter.dateStyle = .longdateFormatter.timeStyle = .shortdateFormatter.doesRelativeDateFormatting = truelet nowString = dateFormatter.string(from: now)print(nowString) // prints: Today at 2:25 PMlet yesterdayString = dateFormatter.string(from: yesterday)print(yesterdayString) // prints: Yesterday at 2:25 PMlet aWeekAgoString = dateFormatter.string(from: aWeekAgo)print(aWeekAgoString) // prints: August 2, 2019 at 2:25 PM


Give this a try

let dateFormatter = NSDateFormatter()dateFormatter.dateStyle = .shortStyledateFormatter.timeStyle = .shortStyledateFormatter.doesRelativeDateFormatting = truelet date = NSDate()let dateString = dateFormatter.stringFromDate(date)