2

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.

4
  • 2
    If I had to guess, I'd say that this is caused by leap seconds accumulated in your calendar since 01/01/0001, so I'd try setting the year. But I just made that up so this may be totally wrong. Commented Jan 15, 2015 at 12:35
  • Interesting … Can you print out the properties of the calendar's time zone property, esp. secondsFromGMT and abbreviation. Commented Jan 15, 2015 at 12:36
  • Regarding my previous comment, setting the year to 2015 did work for me, give or take a few hours caused by my timezone. Commented Jan 15, 2015 at 12:38
  • 1
    Note that the spec says: "When there are insufficient components provided to completely specify an absolute time, a calendar uses default values of its choice." So "odd" the seconds value is, at the very least, not unexpected. And, although the NSDate scheme does not account for leap seconds, the time zone scheme has been changed several times over the centuries; in particular, the switch to time zones from "local noon" time. Commented Jan 15, 2015 at 12:45

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

We read the documentation, but there were doubts in the fact how it works. Thx.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.