与NSDate的问题我正在删除年份,但需要0001年

时间:2013-07-19 06:43:15

标签: ios nsdate nsdateformatter

下面是我的代码,我会解释其中的内容

NSDateFormatter *formater = [[NSDateFormatter alloc] init] ;
[formater setDateFormat:@"MM-dd"];


NSCalendar *calendar = [NSCalendar currentCalendar];
NSInteger desiredComponents = (NSDayCalendarUnit | NSMonthCalendarUnit);


NSDateComponents *firstComponents = [calendar 
              components:desiredComponents fromDate:fDate];
NSDateComponents *secondComponents = [calendar 
             components:desiredComponents fromDate:eDate];
NSDateComponents *thirdComponents = [calendar 
              components:desiredComponents fromDate:mdate];

NSDate *from = [calendar dateFromComponents:firstComponents];
NSDate *end = [calendar dateFromComponents:secondComponents];
NSDate *middle = [calendar dateFromComponents:thirdComponents];

NSString * froms = [formater stringFromDate:from];
NSLog(@"sringfroms:%@",froms);
NSLog(@"datefrom:%@",from);


NSString * ends = [formater stringFromDate:from];
NSLog(@"sringends:%@",ends);
NSLog(@"dateend:%@",end);

NSString * middles = [formater stringFromDate:from];
NSLog(@"sringmiddles:%@",middles);
NSLog(@"datemiddle:%@",middle);

这就是印刷品。

sringfroms:06-30
datefrom:0001-06-29 18:06:32 +0000
sringends:06-30
dateend:0001-08-02 18:06:32 +0000
sringmiddles:06-30
datemiddle:0001-07-14 18:06:32 +0000

您可以看到我从日期中删除了以字符串形式打印的年份,但是当我创建日期时,它会自动获取0001。我正在使用kal日历,我只想标记月和日,所以它应该每年标记

if (([middle compare:from] == NSOrderedDescending) 
          &&([middle compare:end] == NSOrderedAscending)) {
    [holidays addObject:[Holiday  holidayNamed:naMMe 
                 birthDate:bDate iDs:aIDDS date:middle]];
}

任何帮助都将受到高度赞赏

2 个答案:

答案 0 :(得分:1)

OKAY,因为您未在以下代码中使用NSYearCalendarUnit

NSInteger desiredComponents = (NSDayCalendarUnit | NSMonthCalendarUnit);

因此NSDate假设0001为默认年份,如果您在上面的代码中添加NSYearCalendarUnit,则会提供正确的年份,如下所示

NSInteger desiredComponents = (NSDayCalendarUnit 
                   | NSMonthCalendarUnit | NSYearCalendarUnit);

答案 1 :(得分:0)

  

好吧,如果你没有任何组件,那么它总是需要   第一个值(01,0001等)是NSCalendar的默认属性,用于解决你的问题   您需要将该日期转换为日期格式的问题。