2
votes

I am trying to produce an NSDate with fixed hour and minutes. I need this to make an equal comparison with other date stored in CoreData.

So far I wrote this code:

NSDate date = [NSDate date];    
unsigned int flags = NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit;   
NSCalendar* calendar = [NSCalendar  currentCalendar];
NSDateComponents* components = [calendar components:flags fromDate:date];
NSDate* newDate = [calendar dateFromComponents:components];

however with a breakpoint in xcode4 I can see the values:

Printing description of date:
2012-01-10 11:20:47 +0000
Printing description of newDate:
2012-01-09 23:00:00 +0000

Why newDate is one day back in respect of date ?

/* EDIT */

I also have tried to set manually all the components, but calendar dateFromComponents always give back same one hour back date, seems ignoring the components.

components.hour=0;
components.minute=0;
components.second=0;
components.timeZone=[NSTimeZone localTimeZone];

This is the description of component after being set:

<NSDateComponents: 0x7464de0>
    TimeZone: Europe/Rome (CET) offset 3600
    Calendar Year: 2012
    Month: 1
    Day: 10
    Hour: 0
    Minute: 0
    Second: 0

which is exactly what I would like to have, but the calculated date with this component is still

Printing description of newDate:
2012-01-09 23:00:00 +0000

I wonder why I cannot get a precise NSDate even with specifying all the components in an NSDateComponents. Just because NSCalendar is ignoring my requirements, what's the meaning of components ?

What am I doing wrong ?

3

3 Answers

3
votes

I guess you are +01:00 time zone. Actually the NSDate always gives values in GMT. So if it is Jan 10th, 00:00, then at the same time GMT time is Jan 9th, 23:00.

Even, while printing the following line

2012-01-10 11:20:47 +0000,

it should have printed 1 hour less than your current time. Please check.

1
votes

Use this....

  NSDate *date = [NSDate date];    
  NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
  [gregorian setLocale:[NSLocale currentLocale]];
  NSDateComponents *nowComponents = [gregorian components:NSYearCalendarUnit |           NSWeekCalendarUnit | NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit fromDate:date];
   NSDate* newDate = [gregorian dateFromComponents:nowComponents];
   NSLog(@"%@\n%@",date,newDate);
0
votes

You may have problems with time zones, try setting a time zone for the calendar.