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 NSDate Get Start of Day

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

Sometimes, we like to give you a bit more capability than you ask for, just so you can reuse our code in more circumstances. Here's a bit of code that will give you the start of the current day as well as the start of any day before or after it:

Here's how you can get the start of today:

  int dayOffset = 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] + dayOffset)];

  NSDate *beginningOfDay = [cal dateFromComponents:calComponents];

In the above code, its the dayOffset integer that gives you the ability to get the start of tomorrow (dayOffset = 1) or yesterday (dayOffset = -1). That should give you plenty of power.

If you found this so helpful that you just want to throw money at us, why not throw it instead at your local charity? And if you don't have any money to throw around, we'll sure take a +1 instead. 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:

Popular Posts

Designed By Seo Blogger Templates