Why am I getting the wrong time with the right time zone?

Why am I getting this output time:

2013-01-12 18: 24: 37.783 Verification of the code [10328: c07] 0001-01-01 17:12:52 +0000

when i run this code:

NSCalendar *calendar = [NSCalendar currentCalendar]; calendar.timeZone = [NSTimeZone localTimeZone]; NSDateComponents *components = [calendar components:NSHourCalendarUnit fromDate:[NSDate date]]; components.hour = 17; components.minute = 47; components.second = 0; NSDate *fire = [calendar dateFromComponents:components]; NSLog(@"%@", fire); 

I tried the default time zone, the system time zone. And it always gives me a result with different minutes and seconds! plus the wrong date 0001-01-01 !!!! Any idea why?

Additional tests:

When running this code:

 NSCalendar *calendar = [NSCalendar currentCalendar]; calendar.timeZone = [NSTimeZone localTimeZone]; NSDateComponents *components = [calendar components:NSHourCalendarUnit fromDate:[NSDate date]]; components.hour = (components.hour + 1) % 24; components.minute = 0; components.second = 0; NSDate *fire = [calendar dateFromComponents:components]; NSLog(@"%@", fire); 

He gives me this result:

2013-01-12 18: 41: 41.552 Verification of the code [10648: c07] 0001-01-01 18:25:52 +0000

2013-01-12 18: 42: 16.274 Verification of the code [10648: c07] 0001-01-01 18:25:52 +0000

2013-01-12 18: 42: 30.310 Verification of the code [10648: c07] 0001-01-01 18:25:52 +0000

+4
source share
2 answers

You measure the components of the year, month, and day.

make:

NSDateComponents *components = [calendar components:NSUIntegerMax fromDate:[NSDate date]];

Now this should give you the correct date.

Side note: since NSCalendarUnit is a bit type for NSUInteger , I pass NSUIntegerMax to retrieve all possible calendar blocks. Thus, I do not need to have a massive bitwise OR operator.

+7
source

You also need to query the year, month, and day using the calendar components: method.

From Apple docs:

The NSDateComponents instance is not responsible for answering questions about a date that goes beyond the information with which it was initialized.

 NSDateComponents *components = [calendar components:NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit | NSHourCalendarUnit fromDate:[NSDate date]]; 

NSLog dates will display the time with the default time zone.

+4
source

All Articles