-1

Why DateComponentsFormatter.localizedString(from:unitsStyle:) does not work for weekday?

let twoDays = DateComponents(day: 2)
let threeWeeks = DateComponents(weekday: 3)

DateComponentsFormatter.localizedString(from: twoDays, unitsStyle: .full) ?? "found nil" // "2 days"
DateComponentsFormatter.localizedString(from: threeWeeks, unitsStyle: .full) ?? "found nil" // returns "found nil"
Leo Dabus
  • 229,809
  • 59
  • 489
  • 571
user14119170
  • 1,191
  • 3
  • 8
  • 21
  • 1
    What exactly do you think `DateComponents(weekday: 3)` would mean? – matt Feb 05 '22 at 21:58
  • Well, I want to have a Text displaying number of weeks between two dates, and only ```weekday``` worked for me in week calculations. Like this: ```let numberOfWeeksBeetwenTwoDates = Calendar.current.dateComponents([.weekdayOrdinal], from: startDate, to: endDate).weekdayOrdinal ?? 0 let numberOfWeeks = DateComponents(weekday: numberOfWeeksBeetwenTwoDates) Text(DateComponentsFormatter.localizedString(from: twoDays, unitsStyle: .full) ?? "found nil")``` – user14119170 Feb 05 '22 at 22:08
  • 1
    You can get now Date, create a second date adding 3 weeks to now and use [RelativeDateTimeFormatter](https://developer.apple.com/documentation/foundation/relativedatetimeformatter).This [Getting the difference between two Dates (months/days/hours/minutes/seconds) in Swift](https://stackoverflow.com/a/27184261/2303865) might help as well – Leo Dabus Feb 05 '22 at 22:32
  • So this an x-y question. If you wanted to know how to display the difference between dates in weeks, you should have asked that, rather than _assuming_ that DateComponents and DateComponentsFormatter was the way. – matt Feb 05 '22 at 22:54

1 Answers1

1

The DateComponents has a property named allowedUnits, weekday is not a legal unit.

The allowed units are:

year month weekOfMonth day hour minute second

see this ref.

navylover
  • 12,383
  • 5
  • 28
  • 41
  • Thank you, and can I use ```weekday``` in calculations, and then ```weekOfMonth``` for DateComponentsFormatter, or will it cause some incompatibility problems? – user14119170 Feb 05 '22 at 22:11