1

I noticed a particular day that refers to two days ago was localised as Yesterday by the formatter. Is there a config to set to make this be 2 days ago instead? Here's code to replicate the issue:

func getDateFromString(_ dateTimeString: String) -> Date {
    let dateFormatter = DateFormatter()
    dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSSSSZ"
    return dateFormatter.date(from:dateTimeString)!
}

let targetDateStr = "2022-02-08T19:50:11.333017Z"
let nowStr = "2022-02-10T16:57:10.000017Z"

let targetDate = getDateFromString(targetDateStr)
let now = getDateFromString(nowStr)

let formatter = RelativeDateTimeFormatter()
formatter.dateTimeStyle = .named
formatter.unitsStyle = .short
let s = formatter.localizedString(for: targetDate, relativeTo: now) // "yesterday"

I noticed that the formatter produces "2 days ago" only after 48 hours have passed, is there a way to change this behaviour so that any hour on 2022-02-08 gets considered 2 days ago?

Edit

Problem solved: need to remove the hours/minutes/etc. info from the date then the formatter behaves as expected. Thanks @Dev

func getDateFromString(_ dateTimeString: String) -> Date {
    let dateFormatter = DateFormatter()
    dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSSSSZ"
    let date = dateFormatter.date(from:dateTimeString)!
    let calendar = Calendar.current
    let components = calendar.dateComponents([.year, .month, .day], from: date)
    return calendar.date(from: components)!
}
mota
  • 5,275
  • 5
  • 34
  • 44
  • I haven't used swift, but does the .date function return a date object that has only the date or both date & time? I imagine it would work if you just compared dates (the yyyy-MM-dd component) and not dates & times. – BeLEEver Feb 10 '22 at 17:16
  • @Dev I was just trying to figure out how to remove the hours/minutes/etc. info from the date to test this out! – mota Feb 10 '22 at 17:18
  • 1
    https://stackoverflow.com/questions/36861732/convert-string-to-date-in-swift – BeLEEver Feb 10 '22 at 17:20

1 Answers1

2

I haven't used swift, but does the .date function return a date object that has only the date or both date & time? I imagine it would work if you just compared dates (the yyyy-MM-dd component) and not dates & times.

Link to thread on removing timestamp components Convert string to date in Swift

BeLEEver
  • 251
  • 4
  • 11