I'm implementing a calendar view, and I'd like it to start at the beginning of the week containing a particular date. Eg. If the target date is Monday, Feb 29, 2016, and the current calendar is set to start on Sunday, I'd like my view to start with Sunday, February 28.
This seems like it should be straightforward:
let calendar = NSCalendar.currentCalendar()
let firstDate = calendar.nextDateAfterDate(targetDate,
matchingUnit: .Weekday,
value: calendar.firstWeekday,
options: .SearchBackwards)
But this fails with:
Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'Exactly one option from the set {NSCalendarMatchPreviousTimePreservingSmallerUnits, NSCalendarMatchNextTimePreservingSmallerUnits, NSCalendarMatchNextTime} must be specified.'
I can get basically what I want with:
let firstDate = calendar.nextDateAfterDate(firstDate,
matchingUnit: .Weekday,
value: calendar.firstWeekday,
options: .MatchPreviousTimePreservingSmallerUnits)?
.dateByAddingTimeInterval(-7 * 84600)
But it seems like a bad practice, since sometimes the number of seconds in a day isn't 86400.
Is there a better way?
The Calendar has a mechanism for finding date at the start of a given time interval (say week of year, or month) that contains a given date:
You can implement this as Date class extension or something. It should returns something like
2020-01-06 00:00:00 +0000
Xcode 11.3 Swift 5
you can use
Calendar
methoddate(from: DateComponents)
passing[.yearForWeekOfYear, .weekOfYear]
components from any date it will return the first day of the week from the calendar used. So if you would like to get Sunday just use Gregorian calendar. If you would like to get the Monday as the first day of the week you can use Calendar.iso8601
as you can see in this answerXcode 8.3.2 • Swift 3.1 or later
usage:
Basically use
and
. For solving of you're problem try to use this code sample:
I had problems with all previous solutions, since they do not take into account user's calendar setting. Next code will be taking into account that.
Swift 4 Solution
I have figured out according to my requirement, where I have find out dates for following.
So, I have created
Date Extension
to get Dates of Current Week and Next Week.CODE
USAGE:
You can modify
Extension
according to your need.Thanks!