0

I am having a filter on a tableView, that has a 'From' and 'To' Months selection.

Month selection, I mean, when I select Month, the datePicker should show Month Year only. And the list should contain last 12 months from today.

I looked at the default UIDatePicker but realized that it is not possible to get only Month-Year. (Reference answer from SO)

Further looking, I found this link that has a custom month-year picker but it shows future 15 years. And, upon selection of any row, nothing happens.

Can someone help me customize it to show last 12 months from today and fetch the result upon selection?

Lohith Korupolu
  • 1,066
  • 1
  • 18
  • 52
  • If your picker is supposed to contain only 12 items use a standard picker and populate the items like "October 2017", "September 2017" etc. – vadian Oct 25 '17 at 09:54
  • but how do I get the last 12 months? Just need some logic to calculate that stuff please? – Lohith Korupolu Oct 25 '17 at 09:56
  • • Use `Calendar`. • Create `DateComponents(day: 1)` and `enumerateDates(startingAfter:matching:options:using:)` backwards until the number of items is reached. • Map the dates with `DateFormatter` to strings. • Populate the picker – vadian Oct 25 '17 at 10:00
  • sorry to ask, but do you have an example? – Lohith Korupolu Oct 25 '17 at 10:01
  • which month should be shown first? and next month should scroll to up or down? – swift2geek Oct 25 '17 at 10:09
  • current month (example: October 2017) to be shown first. and show previous 12 months from current month. (example October 2017, Sep '17, Aug '17, .... Nov '16 – Lohith Korupolu Oct 25 '17 at 10:10

1 Answers1

1

This is a simple example to get the last 12 months

var last12Months = [Date]()
let firstDayComponent = DateComponents(day: 1)
Calendar.current.enumerateDates(startingAfter: Date(), 
                 matching: firstDayComponent, 
                 matchingPolicy: .nextTime, 
                 direction: .backward, 
                 using: { (date, idx, stop) in
    if let date = date {last12Months.append(date) }
    if last12Months.count == 12 { stop = true }
})

print(last12Months)
let formatter = DateFormatter()
formatter.dateFormat = "MMMM yyyy"
print(last12Months.map({formatter.string(from: $0)}))
vadian
  • 274,689
  • 30
  • 353
  • 361