2

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"
Dávid Pásztor
  • 51,403
  • 9
  • 85
  • 116
SwiftDeveloper
  • 7,244
  • 14
  • 56
  • 85
  • Maybe [Convert string to DATE type in swift 3](https://stackoverflow.com/questions/41435857/convert-string-to-date-type-in-swift-3) will help? – Wiktor Stribiżew Aug 17 '17 at 10:43
  • @WiktorStribiżew this question is not about generating a `Date` object from a date string, but rather about getting a `Date` object from `DateComponents` and generating a String representation from that – Dávid Pásztor Aug 17 '17 at 10:56

1 Answers1

8

You just have to convert the strings into Ints, 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
Dávid Pásztor
  • 51,403
  • 9
  • 85
  • 116
  • Really trapped into this by using `year` instead of `yearForWeekOfYear`. Had to read your answer twice, to notice that your solution indeed works – d4Rk Sep 26 '20 at 15:59