Swift – The beginning of the week and end day last week

Today is Friday, March 6. How to find that February 16 is the start date, and February 22 is the end date of the week before the previous week.
16 is my country Bulgaria will be 15 and 21 in the US I use .currentCalendar()
something like this should work:

< /p>

let cal = NSCalendar.currentCalendar()

let components = NSDateComponents()
components.weekOfYear -= 1
< br />if let date = cal.dateByAddingComponents(components, toDate: NSDate(), options: NSCalendarOptions(0)) {
var beginningOfWeek: NSDate?
var weekDuration = NSTimeInterval()
if cal.rangeOfUnit(.CalendarUnitWeekOfYear, startDate: &beginningOfWeek, interval: &weekDuration, forDate: date) {
let endOfWeek = beginningOfWeek?.dateByAddingTimeInterval(weekDuration)
print(beginningOfWeek) // Optional(2015-02 -15 05:00:00 +0000)
print(endOfWeek) // Optional(2015-02-22 05:00:00 +0000)
}
}

< /div>

Today is Friday, March 6. How to find that February 16 is the start day, and February 22 is the end day of the week before the previous week.
16 is my country, Bulgaria In the U.S. it will be 15 and 21 I use.curren tCalendar()

Things like this should work:

let cal = NSCalendar.currentCalendar()

let components = NSDateComponents()
components.weekOfYear -= 1

if let date = cal.dateByAddingComponents(components, toDate: NSDate(), options: NSCalendarOptions( 0)) {
var beginningOfWeek: NSDate?
var weekDuration = NSTimeInterval()
if cal.rangeOfUnit(.CalendarUnitWeekOfYear, startDate: &beginningOfWeek, interval: &weekDuration, forDate: date) {
let endOfWeek = beginningOfWeek?.dateByAddingTimeInterval(weekDuration)
print(beginningOfWeek) // Optional(2015-02-15 05:00:00 +0000)
print(endOfWeek) // Optional(2015 -02-22 05:00:00 +0000)
}
}

Leave a Comment

Your email address will not be published.