Reputation: 7368
I have myYear
and myWeek
strings comes from apis , I want to convert them to date
string like YYYY-mm-dd how can I do it in swift 3 ? my strings under below.
let myYear = "2017"
let myWeek = "8"
Upvotes: 2
Views: 2319
Reputation: 54785
You just have to convert the strings into Int
s, then generate a DateComponents
object from them, get a Date
from the DateComponents
through a Calendar
and finally use a DateFormatter
to get the expected String representation of the date.
Bear in mind that the Date
object will represent the first second of the week of that year and hence the String representation will correspond to the first day of that week.
let yearString = "2017"
let weekOfYearString = "8"
guard let year = Int(yearString), let weekOfYear = Int(weekOfYearString) else {return}
let components = DateComponents(weekOfYear: weekOfYear, yearForWeekOfYear: year)
guard let date = Calendar.current.date(from: components) else {return}
let df = DateFormatter()
df.dateFormat = "yyyy-MM-dd"
let outputDate = df.string(from: date) //2017-02-19
Upvotes: 9