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 Get First Day of Year

So, you want an NSDate representing the start of this year, huh?

Well, what's the fun in just getting the start of the current year. Here's a bit of code that will give you the start of the current year as well as the start of any year before or after it:

Here's how you can get the start of this year:

  // Lets get the start of this year, but we could do next year (1) or last year (-1)
  int yearOffset = 0;
  // Date representing right now
  NSDate *date = [[NSDate alloc] init];
  NSCalendar *cal = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
  NSDateComponents * calComponents = [cal components: NSYearCalendarUnit fromDate:date];

  [calComponents setYear:([calComponents year] + yearOffset)];

  NSDate *startOfYearWithOffset = [cal dateFromComponents:calComponents];

In the above code, its the yearOffset that gives you the ability to get the start of next year (yearOffset = 1) or last year (yearOffset = -1). Hope that helps you.

If you love us with undying passion for what we just taught you, then please give us a +1 and tell your next door neighbors about us... you've been needing a good excuse to introduce yourself anyway.

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