1

Code:-

let addedTime = dictMessage?.object(forKey: "added_time") as? String
let timeinterval : TimeInterval = (addedTime as NSString).doubleValu                
let dateFromServer = NSDate(timeIntervalSince1970:timeinterval)
let dateFormater : DateFormatter = DateFormatter()              
dateFormater.dateFormat = "dd-MMM-yyyy hh:mm a"
cellDetailsShop.lblTimeShop?.text = dateFormater.string(from: dateFromServer as Date)

I have a json and from json i m getting Timestamp which i already converted to Date.Date which i am receiving it is showing in the format "dd-MMM-yyyy hh:mm a".But i want to show date like if date is of today then it will show :Today 04:55 PM,if date is of yesterday then i will show like: Yesterday 5 PM and if before that then it should show as i am retrieving from JSON. I searched various links but could not find the answer.Could someone help me.Thanks in advance.

Dilip Tiwari
  • 1,441
  • 18
  • 31
  • Apple dateformatter doesnt do this. You have to do this by urself or use any framework or pod if available. – dahiya_boy Jan 18 '18 at 11:49
  • take a ref of link. https://stackoverflow.com/questions/39345101/swift-check-if-a-timestamp-is-yesterday-today-tomorrow-or-x-days-ago – Ankit Chauhan Jan 18 '18 at 11:51
  • 2
    @DilipTiwari Why you begging to each developer, we are here to assist you, not to do your project, please keep in mind. Now you have enough resources are available, so it urself. – dahiya_boy Jan 18 '18 at 12:18

4 Answers4

1

Use the following code

   func relativeDate(for date:Date) -> String {
        let components = Calendar.current.dateComponents([.day, .year, .month, .weekOfYear], from: date, to: Date())
        if let year = components.year, year == 1{
            return "\(year) year ago"
        }
        if let year = components.year, year > 1{
            return "\(year) years ago"
        }
        if let month = components.month, month == 1{
            return "\(month) month ago"
        }
        if let month = components.month, month > 1{
            return "\(month) months ago"
        }

        if let week = components.weekOfYear, week == 1{
            return "\(week) week ago"
        }
        if let week = components.weekOfYear, week > 1{
            return "\(week) weeks ago"
        }

        if let day = components.day{
            if day > 1{
                return "\(day) days ago"
            }else{
                "Yesterday"
            }
        }
        return "Today"
    }
Jayachandra A
  • 1,335
  • 1
  • 10
  • 21
1

As from Calendar object you can get if the date is today or yesterday. based on that you can set String as you like. I've created an example like you need. below is code.

var yesterdayStr = "17-Jan-2018 10:23 AM"
var todayStr = "18-Jan-2018 10:23 AM"
var tomorrowStr = "19-Jan-2018 10:23 AM"
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "dd-MMM-yyyy hh:mm a"
let yesterDaydate = dateFormatter.date(from: yesterdayStr)
let todayDate = dateFormatter.date(from: todayStr)
let tomorrowDate = dateFormatter.date(from: tomorrowStr)
let anotherDateFormatter = DateFormatter()
anotherDateFormatter.dateFormat = "hh:mm a"
if Calendar.current.isDateInYesterday(yesterDaydate!)
{
    let yesterdayDisplayString = "Yesterday, " + anotherDateFormatter.string(from: yesterDaydate!)
}
if Calendar.current.isDateInToday(todayDate!) {
    let todayDisplayString = "Today, " + anotherDateFormatter.string(from: todayDate!)
}
if Calendar.current.isDateInToday(tomorrowDate!) {

}
else {
    let anotherDisplayString = anotherDateFormatter.string(from: tomorrowDate!)
}

and here is output, Output of date Formatter

Mrugesh Tank
  • 3,495
  • 2
  • 29
  • 59
  • date format is same as you need, so I gave you outputString which you need to set in your label. Can't you do this on your own? – Mrugesh Tank Jan 18 '18 at 12:23
  • I've just added 3 dates for an example to make every condition true. you just need to put core logic in your code – Mrugesh Tank Jan 18 '18 at 12:25
1

You can do like this.

let addedTime = dictMessage?.object(forKey: "added_time") as? String
let timeinterval : TimeInterval = (addedTime as NSString).doubleValue
let dateFromServer = NSDate(timeIntervalSince1970:timeinterval)
let dateFormater : DateFormatter = DateFormatter()
if Calendar.current.isDateInToday(dateFromServer) {
    dateFormater.dateFormat = "'Today' hh:mm a"
}
else if Calendar.current.isDateInYesterday(dateFromServer) {
    dateFormater.dateFormat = "'Yesterday' hh:mm a"
}
else {
    dateFormater.dateFormat = "dd-MMM-yyyy hh:mm a"
}
cellDetailsShop.lblTimeShop?.text = dateFormater.string(from: dateFromServer as Date)

Let me know if you have any comment.

Thanks.

MinuMaster
  • 1,457
  • 1
  • 13
  • 29
0

If you can do it without a custom date format DateFormatter provides localized relative formatting. The date format considers the settings in System Preferences.

let dateFromServer = Date(timeIntervalSinceNow: -100000)
let dateFormatter = DateFormatter()
dateFormatter.doesRelativeDateFormatting = true
dateFormatter.timeStyle = .short
dateFormatter.dateStyle = .short
let string = dateFormatter.string(from: dateFromServer)

Please don't use Foundation NSString and NSDate in Swift, use the native structs

if let addedTime = dictMessage?["added_time"] as? String,
    let timeinterval = TimeInterval(addedTime) {
        let dateFromServer = Date(timeIntervalSince1970:timeinterval)
        let dateFormater = DateFormatter() 
        ...
}
vadian
  • 274,689
  • 30
  • 353
  • 361