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)

Monday, December 16, 2013

iOS NSDate Beginning of Week

So, you want to get a NSDate object representing the beginning of this week, eh?

Well, how about a bit of code that will not only give you the start of the current week, but the week before and the week before that, as well as the weeks following? What do you say? If you're interested, this is how you do it:

  int weekOffset = 0;
  NSDate *rightNow = [[NSDate alloc] init];
  NSCalendar *cal = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
  NSDateComponents *calComponents = [cal components:( NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit ) fromDate:rightNow];
  // Current day of week, with hours, minutes and seconds zeroed-out
  int today = [[[NSCalendar currentCalendar] components:NSWeekdayCalendarUnit fromDate:rightNow] weekday];
  [calComponents setDay:([calComponents day] - ((today) - 1) + (7 * weekOffset))];
  NSDate *startOfWeek = [cal dateFromComponents:calComponents];

In the above code, its the weekOffset integer that gives you the power for getting the start of weeks past and present. Set it to -1 for the beginning of last week, or 1, for the beginning of next week. A nice bit of code that will save you some frustration, I'll wager.

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:

Popular Posts

Designed By Seo Blogger Templates