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)!
}
CodePudding user response:
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