Reputation: 67
Please help me with non-obvious code behavior
NSCalendar *calendar = [NSCalendar currentCalendar];
NSDateComponents *dateComponents = [[NSDateComponents alloc] init];
dateComponents.hour = 15;
dateComponents.minute = 20;
dateComponents.calendar = calendar;
NSDate * endDate = [calendar dateFromComponents:dateComponents];
EndDate is 0001-01-01 12:49:43 +0000. Why?
Hours value may be incorrect due to the difference in the time zones. Why such strange minutes and seconds value? Regards.
Upvotes: 2
Views: 77
Reputation: 20155
If we are just considering the following code snippet
NSCalendar *calendar = [NSCalendar currentCalendar];
NSDateComponents *components = [[NSDateComponents alloc] init];
[components setCalendar:calendar];
NSDate *date = [calendar dateFromComponents:components];
date = 0000-12-31 23:06:32 +0000
, because:
Calendars encapsulate information about systems of reckoning time in which the beginning, length, and divisions of a year are defined.
[...]
When there are insufficient components provided to completely specify an absolute time, a calendar uses default values of its choice. Apple Documentation
and
An
NSDateComponents
object is meaningless in itself; you need to know what calendar it is interpreted against, and you need to know whether the values are absolute values of the units, or quantities of the units. Apple Documentation
Actually, everything is fine and exactly what the documentation says.
Upvotes: 1