NSDateComponents今年最后一周的周成分

时间:2012-12-24 08:49:10

标签: iphone ios nsdatecomponents

一年有多少个星期?因为我在网上搜索过,我发现一年总共52.1周,但如果我在Xcode中这样做:

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

[gregorian setFirstWeekday:2];

NSDate* sourceDate = [NSDate date];

NSTimeZone* sourceTimeZone = [NSTimeZone timeZoneWithAbbreviation:@"GMT"];
NSTimeZone* destinationTimeZone = [NSTimeZone systemTimeZone];

NSInteger sourceGMTOffset = [sourceTimeZone secondsFromGMTForDate:sourceDate];
NSInteger destinationGMTOffset = [destinationTimeZone secondsFromGMTForDate:sourceDate];
NSTimeInterval interval = destinationGMTOffset - sourceGMTOffset;

NSDate* today = [[NSDate alloc] initWithTimeInterval:interval sinceDate:sourceDate];

NSDateComponents *todaysComponents = [gregorian components:NSWeekCalendarUnit fromDate:today];

NSUInteger todaysWeek = [todaysComponents week];

今日周刊的价值是: 53 ,怎么可能?为什么不是52?

2 个答案:

答案 0 :(得分:1)

他们将52.1转换为53 ...最好显示多于截断小数部分。

这也取决于一周的开始日。

欧洲和ISO标准(周一至周日) - 52周完整周,短期(1天)周,占1月1日星期日,短期(1天)周,占12月31日星期一,共计54周。

U.S。标准(从周日到周六) - 完整的52周,以及12月30日和31日的短暂(2天)周,共计53周。

从周六到周五 - 整整51周,短期(6天)一周占1月1日至1月6日,短期(3天)周占12月29日至12月31日,共计53周。

编辑:

由于iOS NSCalender似乎相应地将ISO 8601定义为默认值。您需要使用方法“setMinimumDaysInFirstWeek”设置日历以获得预期的周数结果。

请添加此代码并检查

    [gregorian setMinimumDaysInFirstWeek:5]; //"5" means Thursday in this case.

http://en.wikipedia.org/wiki/ISO_week_date“一年的第一周是包含一年中第一个星期四的一周。”

编辑2:

用于检查一年中可能的最小/最大周数

NSCalendar *gregorian = [[NSCalendar alloc]initWithCalendarIdentifier:NSGregorianCalendar];
int minWeeks, maxWeek;
minWeeks=maxWeek=0;
for (int weekCounter=1; weekCounter<=7; weekCounter++) {
    [gregorian setMinimumDaysInFirstWeek:weekCounter];
    [gregorian setFirstWeekday:2];
    NSDate* sourceDate = [NSDate date];
    NSTimeZone* sourceTimeZone = [NSTimeZone timeZoneWithAbbreviation:@"GMT"];
    NSTimeZone* destinationTimeZone = [NSTimeZone systemTimeZone];
    NSInteger sourceGMTOffset = [sourceTimeZone secondsFromGMTForDate:sourceDate];
    NSInteger destinationGMTOffset = [destinationTimeZone secondsFromGMTForDate:sourceDate];
    NSTimeInterval interval = destinationGMTOffset - sourceGMTOffset;
    NSDate* today = [[NSDate alloc] initWithTimeInterval:interval sinceDate:sourceDate];
    NSDateComponents *todaysComponents = [gregorian components:NSWeekCalendarUnit fromDate:today];
    NSUInteger todaysWeek = [todaysComponents week];

    if (todaysWeek>maxWeek) {
        maxWeek=todaysWeek;
    }
    if (todaysWeek<minWeeks || minWeeks==0) {
        minWeeks=todaysWeek;
    }
}
NSLog(@"min:%d, max:%d", minWeeks, maxWeek);

答案 1 :(得分:0)

您可以尝试使用代码吗?

NSDate *date = [NSDate date];
NSDateFormatter *weekFormatter = [[NSDateFormatter alloc] init];
[weekFormatter setDateFormat:@"w"];
NSString *weekDateString = [weekFormatter stringFromDate:date];
NSLog(@"week = %@",weekDateString);
[weekFormatter release];

您可以使用以上代码获取一周的周数。但该数字基于当前日历和区域设置。