получить NSDate от дня года - PullRequest
1 голос
/ 20 ноября 2010

У меня есть день года, например, 346. Я хочу узнать NSDate, какой месяц и день это означает.

Ответы [ 2 ]

2 голосов
/ 21 ноября 2010

Ваши шаги здесь:

  • Создание календаря
  • Построение даты с 1 января года
  • Добавление количества дней - 1 и построениедата с этим
  • Получить интересующие вас компоненты

Следите, если полученная вами дата основана на 0 или 1.

NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];

NSDateComponents *comps = [[NSDateComponents alloc] init];
[comps setYear:theYear];
[comps setMonth:1];
[comps setDay:1];
NSDate *date = [gregorian dateFromComponents:comps];
[comps release];

NSDateComponents *compsToAdd = [[NSDateComponents alloc] init];
[comps setDay:theDay-1];

NSDate *finalDate = [gregorian dateByAddingComponents:compsToAdd date options:0];

[compsToAdd release]

NSDateComponents *interestingComponents =  [gregorian components:(NSDayCalendarUnit | NSMonthCalendarUnit) fromDate:finalDate];
NSInteger day = [interestingComponents day];
NSInteger month = [interestingComponents month];

[gregorian release];
0 голосов
/ 21 ноября 2010

См. -dateByAddingComponents:toDate:options: метод NSCalendar.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...