Reputation: 313
I have a .compactmap function which gets all the dates from the past week and returns them in a Date array:
func getCurrentWeek() -> [Date]{
let calendar = Calendar.current
let today = calendar.startOfDay(for: Date())
let dayOfWeek = calendar.component(.weekday, from: today)
let weekdays = calendar.range(of: .weekday, in: .weekOfYear, for: today)!
let days = (weekdays.lowerBound ..< weekdays.upperBound)
.compactMap { calendar.date(byAdding: .day, value: $0 - dayOfWeek, to: today) } // use `compactMap` in Xcode 9.3 and later
.filter { !calendar.isDateInWeekend($0) }
return days
}
I am trying to use this as a label and I need it to be in string format but cannot seem to change the function to return an array of strings. I have tried this:
func getCurrentWeek() -> [String]{
let calendar = Calendar.current
let today = calendar.startOfDay(for: Date())
let dayOfWeek = calendar.component(.weekday, from: today)
let weekdays = calendar.range(of: .weekday, in: .weekOfYear, for: today)!
let formatter = DateFormatter()
formatter.dateStyle = .short
formatter.timeStyle = .none
let days = (weekdays.lowerBound ..< weekdays.upperBound)
.compactMap { calendar.date(byAdding: .day, value: $0 - dayOfWeek, to: today) } // use `compactMap` in Xcode 9.3 and later
.filter { !calendar.isDateInWeekend($0) }
let myStringafd = formatter.string(from: days)
return myStringafd
}
But keep getting this error:
Cannot convert value of type '[Date]' to expected argument type 'Date'
I know what this means but I'm not sure how to get past this problem and fix the error?
Current format:
[2018-04-08 23:00:00 +0000, 2018-04-09 23:00:00 +0000, 2018-04-10 23:00:00 +0000, 2018-04-11 23:00:00 +0000, 2018-04-12 23:00:00 +0000]
Desired Format:
["2018-04-08", "2018-04-09", "2018-04-10", "2018-04-11", "2018-04-12"]
Upvotes: 0
Views: 2143
Reputation: 1822
You can also try:
for date in arrOfDates{
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd"
let convdate = dateFormatter.string(from: date)
print(convdate)
}
Upvotes: 0
Reputation: 100503
The problem is here
let myStringafd = formatter.string(from: days)
this takes single Date as argument,but you're passing days
which is array of Dates , you have to
return days.map{ formatter.string(from: $0) }
Upvotes: 2