Ready to Level-Up?

This just in! If your rusty iOS skills could use some refining, or if you're just starting out and you want to level-up fast, consider signing up for our upcoming iOS Screencasts

New from iOS Rocket Surgery Swift Video Tutorials: The rapidly evolving Apple-iOS ecosystem has just been thrown into tumult with the recent introduction of the Swift Programming Language. Are you ready to finally try iOS development? Are you needing to switch from Objective-C to Swift? Sign up today for our free video courses!
(By the dear folks at Swift Tutorial Videos, a sister company)

Thursday, December 19, 2013

iOS Last Day of Week

So, you'd like to get an NSDate representing the last day of the current week, huh?

Well, firstly, lets define what we mean by last day of the week. Of course, we mean Saturday, why wouldn't we, right? Well, there tends to be a lot of discussion around this, and we don't want to meddle with ongoing debates on the merits of treating Sunday as the last day of the week. For our purposes, Sunday is the first day of the week, and Saturday is the last day of the week.

Here's a quick example of how to get the (beginning of) the last day of the week:

  NSCalendar *cal = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];

  NSDate *date = [[NSDate alloc] init];
  
  NSDateComponents *calComponents = [cal components:( NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit ) fromDate:date];

  // this will give you current day of week
  int dayofweek = [[[NSCalendar currentCalendar] components:NSWeekdayCalendarUnit fromDate:date] weekday];
  
  // Offset to Saturday
  int dayOfWeekOffset = 6;
  
  // this will give you Saturday (the last day of the week)
  [calComponents setDay:([calComponents day] - ((dayofweek) - 1) + dayOfWeekOffset)];

  NSDate *lastDayOfWeek = [cal dateFromComponents:calComponents];

That seems like a lot of code, but all you are doing is breaking down dates into their components and adding and/or subtracting components. Its easy to get it mixed up in your head the first go-round. Best of luck!

If you're viewing this page as a castaway from a deserted island somewhere in the Pacific and you need help, reach out to us, otherwise, if you found this post useful, please give us a +1, thanks!




About Me

Easy NSDateFormatter Tool

Save yourself some time in formatting your NSDates to NSStrings, and use the Blind NSDate app, which you can download from iTunes. There's also a website where you can format your NSDates: http://www.blindnsdate.com

Popular Posts

Designed By Seo Blogger Templates