ios版本的不同日期范围

时间:2013-08-19 06:39:09

标签: ios xcode simulator

调用模拟器的方法时 版本6.1显示:
 年--- 2012
 周没有 - 52
 平日--- 2
 结果日期--- 2012-12-16 18:30:00 +0000
 日期时间是2012年12月17日至2012年12月23日
 版本5.0显示:
 年--- 2012
 周没有 - 52
 平日--- 2
  resultdate --- 2012-12-23 18:30:00 +0000  日期时间是24日结束。 2012年至30日。 2012

 NSCalendar *gregorian                               = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
gregorian.Locale                                    = [NSLocale currentLocale];
//[gregorian setTimeZone:[NSTimeZone timeZoneWithName:@"GMT"]];
gregorian.firstWeekday                              = 2; // Sunday = 1, Saturday = 7


NSDateComponents *components                        = [gregorian components:NSYearForWeekOfYearCalendarUnit |NSWeekOfYearCalendarUnit |NSWeekdayOrdinalCalendarUnit fromDate:[NSDate date]];

[components setYearForWeekOfYear:2012];
[components setWeekOfYear:52];
[components setWeekdayOrdinal:2];
NSLog(@"year---%ld",(long)[components yearForWeekOfYear]);
NSLog(@"week no---%ld",(long)[components weekOfYear]);
NSLog(@"weekday---%ld",(long)[components weekdayOrdinal]);

NSDate                  *resultDate                 = [gregorian dateFromComponents:components];
NSLog(@"resultdate---%@",resultDate);
NSDate                  *startOfTheWeek;
NSDate                  *endOfWeek;
NSTimeInterval          interval;
[gregorian rangeOfUnit:NSWeekOfYearCalendarUnit startDate:&startOfTheWeek interval:&interval forDate:resultDate];
endOfWeek                                           = [startOfTheWeek dateByAddingTimeInterval:interval-1];

并且使用的输出日期格式是

NSDateFormatter* dateFormatter          = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"dd MMM yyyy"];
    NSString *str_StartOfTheWeek            = [dateFormatter stringFromDate:startOfTheWeek];
    NSString *str_EndOfWeek                 = [dateFormatter stringFromDate:endOfWeek];
    NSLog(@"date time is %@",[NSString stringWithFormat:@"%@ To %@",str_StartOfTheWeek,str_EndOfWeek]);
    return                                 [NSString stringWithFormat:@"%@ To %@",str_StartOfTheWeek,str_EndOfWeek];

如何解决这个问题请帮忙。

1 个答案:

答案 0 :(得分:0)

要设置工作日(例如2 =周一),您必须使用NSWeekdayCalendarUnitsetWeekday:,而不是NSWeekdayOrdinalCalendarUnitsetWeekdayOrdinal:

NSDateComponents *components = [gregorian components:NSYearForWeekOfYearCalendarUnit|NSWeekOfYearCalendarUnit|NSWeekdayCalendarUnit
                        fromDate:[NSDate date]];
[components setYearForWeekOfYear:2012];
[components setWeekOfYear:52];
[components setWeekday:2];

通过此修改,输出为

date time is 17 Dec 2012 To 23 Dec 2012
iOS 5和iOS 6上的