@@ -57,6 +57,46 @@ extension Date {
5757 return Strings . presentDeicticExpression
5858 }
5959
60+ /// Returns a localized string used for describe a date range string based on two dates. E.g.
61+ ///
62+ /// receiver: 2021-01-01
63+ /// other: 2022-12-31
64+ /// returns: Jan 1, 2021 - Dec 31, 2022
65+ ///
66+ /// receiver: 2021-01-01
67+ /// other: 2021-01-31
68+ /// returns: Jan 1 - 31, 2022
69+ ///
70+ /// receiver: 2021-01-01
71+ /// other: 2022-01-01
72+ /// returns: Jan 1, 2021 - Jan 1, 2022
73+ ///
74+ /// receiver: 2022-01-1
75+ /// other: nil
76+ /// returns: Jan 1, 2022
77+ ///
78+ func formatAsRange( with other: Date ? = nil , timezone: TimeZone , calendar: Calendar ) -> String {
79+ guard let other else {
80+ return DateFormatter . Stats. createDayMonthYearFormatter ( timezone: timezone) . string ( from: self )
81+ }
82+
83+ let formattedStart : String
84+ if self . isSameYear ( as: other, using: calendar) {
85+ formattedStart = DateFormatter . Stats. createDayMonthFormatter ( timezone: timezone) . string ( from: self )
86+ } else {
87+ formattedStart = DateFormatter . Stats. createDayMonthYearFormatter ( timezone: timezone) . string ( from: self )
88+ }
89+
90+ let formattedEnd : String
91+ if self . isSameMonth ( as: other, using: calendar) {
92+ formattedEnd = DateFormatter . Stats. createDayYearFormatter ( timezone: timezone) . string ( from: other)
93+ } else {
94+ formattedEnd = DateFormatter . Stats. createDayMonthYearFormatter ( timezone: timezone) . string ( from: other)
95+ }
96+
97+ return " \( formattedStart) - \( formattedEnd) "
98+ }
99+
60100 /// Returns the next midnight starting from `self`.
61101 ///
62102 /// For example, if `self` is 2020-01-03 00:41:09, the returned value will be 2020-01-04 00:00:00.
0 commit comments