0

Why the following code prints me "Tomorrow" and not "In 2 days"?

let dateString = "2022-05-21"

let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd"

let date = dateFormatter.date(from: dateString)!

print(date)
print(Calendar.current.dateComponents([.day, .month, .year], from:date))

let relativeDateTimeFormatter = RelativeDateTimeFormatter()
relativeDateTimeFormatter.dateTimeStyle = .named
relativeDateTimeFormatter.formattingContext = .beginningOfSentence

let now = Date()  // Today is 2022-05-19

print(now)

let dateComponents = Calendar.current.dateComponents([.year, .month, .day], from: now, to: date)

print(dateComponents)

print(relativeDateTimeFormatter.localizedString(from: dateComponents))


The full console log is

2022-05-20 22:00:00 +0000
year: 2022 month: 5 day: 21 isLeapMonth: false 
2022-05-19 15:44:00 +0000
year: 0 month: 0 day: 1 isLeapMonth: false 
Tomorrow
Giorgio
  • 1,973
  • 4
  • 36
  • 51
  • 1
    What's the "full" value of `date` and `now` and `dateComponents`? – Larme May 19 '22 at 15:41
  • If you look closely, the difference isn't coming from the formatter, but from `Calendar.dateComponents`. `dateComponents.day` is 1, not 2. As soon as you apply the answer from the linked duplicate to your `dateComponents` calculation, you'll get the expected result. – Dávid Pásztor May 19 '22 at 15:44
  • Ok, with `startOfDay`it works! But I don't understand why `print(Calendar.current.dateComponents([.day, .month, .year], from:date))` prints me **year: 2022 month: 5 day: 21 isLeapMonth: false**; `print(Calendar.current.dateComponents([.day, .month, .year], from:now))` prints me **year: 2022 month: 5 day: 19 isLeapMonth: false**; but the difference prints me **year: 0 month: 0 day: 1 isLeapMonth: false** – Giorgio May 19 '22 at 15:56
  • `dateComponents(from:to:)` compares the full date objects, not just the specified components, so if the difference between 2 dates is 1 day 23 hours, the `day` component of the returned value will be 1, not 2, since there aren't 2 full days difference between the 2 dates. – Dávid Pásztor May 19 '22 at 16:16
  • Thank you @DávidPásztor. Maybe the Apple `dateComponents(from:to:)` func documentation is a little confusing. It says for `components` parameter: Which components to compare. So I thought only components in `components`were used to compare. – Giorgio May 19 '22 at 16:22

0 Answers0