Reputation: 91
In Swift I need to get the month name and week of:
example: June 2 - 8
I have created an extension to Date() class and I do get the month name, but it is abbreviated and the weeks are printed out with Optional().
So I need for the week this. 2 - 8. I know the - can just be in a string literal so I am not worried about that.
extension Date {
func monthAsString() -> String {
let df = DateFormatter()
df.setLocalizedDateFormatFromTemplate("MMM")
return df.string(from: self)
}
func startOfWeek() -> String? {
let gregorian = Calendar(identifier: .gregorian)
let sunday = gregorian.date(from: gregorian.dateComponents([.yearForWeekOfYear, .weekOfYear], from: self))!
return String(describing: gregorian.date(byAdding: .day, value: 1, to: sunday))
}
func endOfWeek() -> String? {
let gregorian = Calendar(identifier: .gregorian)
let sunday = gregorian.date(from: gregorian.dateComponents([.yearForWeekOfYear, .weekOfYear], from: self))!
return String(describing: gregorian.date(byAdding: .day, value: 7, to: sunday))
}
}
in a UILabel I need to show something like this:
June 2 - 8 or September 22 - 28
like that.
Upvotes: 0
Views: 216
Reputation: 318824
First, use "MMMM"
, not "MMM"
to get the full month name.
Next, never use String(describing:)
for anything except for debugging.
A better solution is to generate the two dates for start and end of week. Then use DateIntervalFormatter
to generate a string from the two dates.
Here's your updated Date extension to generate Date instead of String:
extension Date {
func startOfWeek() -> Date? {
let gregorian = Calendar(identifier: .gregorian)
if let sunday = gregorian.date(from: gregorian.dateComponents([.yearForWeekOfYear, .weekOfYear], from: self)) {
return gregorian.date(byAdding: .day, value: 1, to: sunday)
} else {
return nil;
}
}
func endOfWeek() -> Date? {
let gregorian = Calendar(identifier: .gregorian)
if let sunday = gregorian.date(from: gregorian.dateComponents([.yearForWeekOfYear, .weekOfYear], from: self)) {
return gregorian.date(byAdding: .day, value: 7, to: sunday)
} else {
return nil
}
}
}
And here's an example showing how to use a DateIntervalFormatter
to give the desired result:
let aDate = Date()
if let sow = aDate.startOfWeek(), let eow = aDate.endOfWeek() {
let formatter = DateIntervalFormatter()
formatter.dateTemplate = "MMMMd"
print(formatter.string(from: sow, to: eow))
}
Output:
September 9 - 15
Upvotes: 1