title: NSDate best practice in creating a date with no time element
body: <p>I am writing an app which uses core-data to store my data. Included in this is a date field of which I am only interested in the date not the time.
  I need to select records based on the date (not time) and so I have created a category on NSDate to return a date, normalised to a set time as follows:</p>
  
  <pre><code>+ (NSDate *)dateWithNoTime:(NSDate *)dateTime {
  if( dateTime == nil ) {
      dateTime = [NSDate date];
  }
  NSDateComponents* comps = [[NSCalendar currentCalendar] components:NSYearCalendarUnit|NSMonthCalendarUnit|NSDayCalendarUnit fromDate:dateTime];
  NSDate *dateOnly = [[NSCalendar currentCalendar] dateFromComponents:comps];
  [dateOnly dateByAddingTimeInterval:(60.0 * 60.0 * 12.0)];           // Push to Middle of day.
  return dateOnly;
  </code></pre>
  
  <p>}</p>
  
  <p>I then use this when I add data to the core-data store (I have a setter which uses this method to set the primitive date value) and then I use this method to create a date that I use to compare the dates when performing a fetch request. So in theory this should always work - ie pick out the dates I'm looking for.</p>
  
  <p>I'm slightly nervous though as I'm not totally sure what effect changing time-zone or locale will have. Will it still work ?</p>
  
  <p>What is considered best practice when storing and searching on a date only when you aren't interested in the time.</p>
  
  <p>Cheers.</p>
  
  <p><strong>EDIT</strong></p>
  
  <p>After reading the discussion recommended I think that I should modify my code to be as follows. The thinking being that if I ensure that I push it to a specific calendar system and a specific timezone (UTC) then the dates should always be the same regardless of where you are when you set the date and when you read the date. Any comments on this new code appreciated.</p>
  
  <pre><code>+ (NSDate *)dateWithNoTime:(NSDate *)dateTime {
  if( dateTime == nil ) {
      dateTime = [NSDate date];
  }
  
  NSCalendar       *calendar   = [[[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar] autorelease];
  [calendar setTimeZone:[NSTimeZone timeZoneWithAbbreviation:@"UTC"]];
  NSDateComponents *components = [[[NSDateComponents alloc] init] autorelease];
  components = [calendar components:NSYearCalendarUnit|NSMonthCalendarUnit|NSDayCalendarUnit
                           fromDate:dateTime];
  
  NSDate *dateOnly = [calendar dateFromComponents:components];
  
  [dateOnly dateByAddingTimeInterval:(60.0 * 60.0 * 12.0)];           // Push to Middle of day.
  return dateOnly;
  </code></pre>
  
  <p>}</p>