Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why am I getting wrong time output with correct timezone?

Why am I getting this output time:

2013-01-12 18:24:37.783 Code testings[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 have tried default timezone, system timezone. And it always gives me an output with different minutes and seconds! plus 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);

It gives me this output:

2013-01-12 18:41:41.552 Code testings[10648:c07] 0001-01-01 18:25:52 +0000

2013-01-12 18:42:16.274 Code testings[10648:c07] 0001-01-01 18:25:52 +0000

2013-01-12 18:42:30.310 Code testings[10648:c07] 0001-01-01 18:25:52 +0000

like image 739
Whylonely Avatar asked Dec 20 '22 11:12

Whylonely


2 Answers

You are mising the year, month and day components.

Do:

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

Now that should give you the correct date.

Side note: since the NSCalendarUnit is a bitfield typedef for NSUInteger, I pass in NSUIntegerMax to retrieve all possible calendar units. That way I don't have to have a massive bitwise OR statement.

like image 182
Peter Warbo Avatar answered Jan 06 '23 04:01

Peter Warbo


You also need to request the year, month and day with the calendar components: method.

From Apple docs:

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

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

NSLog of the date will display the time with the default timezone.

like image 43
zaph Avatar answered Jan 06 '23 05:01

zaph