Swift Month year pickerView with last 12 months - ios

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?

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)}))

Related

UISegment Control - Set selected according to day (SWIFT)

Like the title says, I'm trying to set the selected segment control according to day. My segment control includes the days of the week and i also have a date and time label. The proper day has to be selected when the view is open
I know i have to do something with:
segmentControl.selectedSegmentIndex = 0
I'm getting the date with:
showDate.text = "Date: " + DateFormatter.localizedString(from: Date(), dateStyle: DateFormatter.Style.medium, timeStyle: .none)
But I'm not sure how to set the selectedIndex to be dependent on date and show the appropriate day. I'm still new to swift and still learning, any help will be very much appreciated! Thanks
UISegmentedControl indexes start from 0. If you have all the days of the week in it its indexes start from 0 and end in 6.
You can get a day's index in weekdays using this
let day = Calendar.current.component(.weekday, from: Date())
this returns 1 for Sunday, 2 for Monday... 7 for Saturday
So you can assign selectedSegmentIndex as follows
if (2...6).contains(day) {
segmentControl.selectedSegmentIndex = day-2
} else {
segmentControl.selectedSegmentIndex = UISegmentedControlNoSegment
}

How to disable specific days in UIDatePicker

I have a UIDatePicker that should show only specific days, like all Sundays and Mondays, and disable all other dates, The user can select only Sunday and Monday from this week, next week, the week after, to, let's say, 2020.
Is that even possible with UIDatePicker, or even any custom control?
I would suggest you to use like this:
From below code you will get dates of all the Sundays from 2016-2018,
let cal = Calendar.current
// Get the date of 2 years ago today
let stopDate = cal.date(byAdding: .year, value: -2, to: Date())!
// We want to find dates that match on Sundays at midnight local time
var comps = DateComponents()
comps.weekday = 1 // Sunday
// Enumerate all of the dates
cal.enumerateDates(startingAfter: Date(), matching: comps, matchingPolicy: .previousTimePreservingSmallerComponents, repeatedTimePolicy: .first, direction: .backward) { (date, match, stop) in
if let date = date {
if date < stopDate {
stop = true // We've reached the end, exit the loop
} else {
print("\(date)") // do what you need with the date
}
}
}
The logic is simple. Make an array of this is in your required dateFormat and show that in pickerView which will eventually work as datePicker for you.
Hope this helps.
This is impossible. You have to create custom date picker based on UIPickerView.
There is a way to do it with just the UIDatePicker!
Lets say you have a minTime that is January 16 10:00AM
You would do something like this:
let picker = UIDatePicker()
picker.minimumDate = minTime
picker.maximumDate = minTime.changing(.hour, value: 23).changing(.minute, value: 59)
Then the picker will be stuck to that date.
Hope this helps someone!

Showing dates of specific weekday in UIDatePicker

I have a UIDatePicker and I want to show only the dates of specific weekday in of the picker.
For example, if I select Mon 26 March then I should only see
2 April,
9 April,
16 April,
23 April
and so on in the UIDatePicker. How can this be achieved using UIDatePicker
I Think there is no build-in functionality that can be used to accomplish this , you can create a pickerView and get week dates by adding this to the current
extension Date
{
var nextDateWeak : Date {
return Calendar.current.date(byAdding: .day, value: 6 , to: self )!
}
}

How can i get a tableview to count a week 1 day per row (ex: monday jun 10th = row 1.. tuesday june 11th row 2) using swift [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
How can i get a tableview to count a week 1 day per row (ex: monday jun 10th = row 1.. tuesday june 11th row 2) timestamped on a label using swift in xcode 7? i know how to get the current time but i need it to count 7 days and leave the date until the week starts over.
You should look at NSDateComponents and NSCalendar. For example if you're looking to get the dates of the current week starting Monday, you can say something like:
func datesForCurrentWeek() -> [NSDate]
{
let date = NSDate()
let calendar = NSCalendar.currentCalendar()
let components = calendar.components([.Weekday], fromDate: date)
let weekday = components.weekday == 1 ? 8 : components.weekday
var weekArray = [NSDate]()
for i in 2 ... 8
{
let components = NSDateComponents()
components.day = i - weekday
weekArray.append(calendar.dateByAddingComponents(components, toDate: date, options: [])!)
}
return weekArray
}
Here you just determine what the current day of the week is, and then create an array that includes it and the six other days that encompass that week. You also need to shift it so Monday is the start of the week, as Sunday is the default.
You can then create a property like "dateStringArray" to hold your dates as strings. For example:
let datesArray = datesForCurrentWeek()
let dateFormatter = NSDateFormatter()
dateFormatter.dateStyle = .FullStyle
self.dateStringArray = datesArray.map{
dateFormatter.stringFromDate($0)
}
Then in your cellForRowAtIndexPath you can populate your cells:
cell.textLabel.text = self.dateStringArray[indexPath.row]
For more information on NSDateComponents see here and here.

List of Days of this week

I need a list of days of the week (with the week starting on Monday) for a timecard list. Im not sure how to achieve this. I have tried some dateByAddingUnit and subtracting from there but it hasn't produced the results I want.
Any idea how to get a list of the dates? (i.e. Monday would be 3/28/16, Tuesday 3/29/16 and so on)
Edit: missed that you want a week to always start on a Monday
let gregorian = NSCalendar(calendarIdentifier: NSCalendarIdentifierGregorian)!
let today = gregorian.startOfDayForDate(NSDate())
let startOfWeek: NSDate
if gregorian.component(.Weekday, fromDate: today) == 2 {
// Today is Monday
startOfWeek = today
} else {
// Find the last Monday prior to today
startOfWeek = gregorian.nextDateAfterDate(today, matchingUnit: .Weekday, value: 2, options: [.SearchBackwards, .MatchPreviousTimePreservingSmallerUnits])!
}

Resources