计算日历周

时间:2010-09-01 12:31:47

标签: iphone objective-c xcode calendar

如何计算日历周?一年有52/53周,有两条规则:

-USA

-DIN 1355 / ISO 8601

我想使用DIN 1355 / ISO 8601.我该如何管理?

修改

NSDate *today = [NSDate date];
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:@"ww"];
NSString *weeknumber = [dateFormat stringFromDate: today];
NSLog(@"week: %@", weeknumber);

取自http://iosdevelopertips.com/cocoa/date-formatter-examples.html

在哪里可以找到允许的日期格式?

5 个答案:

答案 0 :(得分:5)

使用NSCalendarNSDateComponents

NSCalendar *cal = [NSCalendar currentCalendar];
NSDateComponents *components = [cal components:NSWeekCalendarUnit fromDate:date];
NSInteger week = [components week];

答案 1 :(得分:1)

或使用:

CFAbsoluteTime currentTime = CFAbsoluteTimeGetCurrent();
CFTimeZoneRef currentTimeZone = CFTimeZoneCopyDefault();    
SInt32 weekNumber = CFAbsoluteTimeGetWeekOfYear(currentTime, currentTimeZone);

编号遵循ISO 8601周定义。

答案 2 :(得分:1)

NSDate *today = [NSDate date];
NSCalendar *ISO8601 = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierISO8601];
ISO8601.firstWeekday = 2; // Sunday = 1, Saturday = 7
ISO8601.minimumDaysInFirstWeek = 4;
NSDateComponents *components = [ISO8601 components:NSCalendarUnitWeekOfYear fromDate:today];
NSUInteger weekOfYear = [components weekOfYear];
NSDate *mondaysDate = nil;
[ISO8601 rangeOfUnit:NSCalendarUnitYearForWeekOfYear startDate:&mondaysDate interval:NULL forDate:today];
NSLog(@"The current Weeknumber of Year %ld ", weekOfYear);

答案 3 :(得分:0)

您应该像这样使用NSDateFormatter

NSDateFormatter *fm = [[NSDateFormatter alloc] initWithDateFormat:@"ww" allowNaturalLanguage:NO];
NSString *week = [fm stringFromDate: date];

答案 4 :(得分:0)

Canlendar有很多种。

Week number according to the ISO-8601 standard, weeks starting on Monday. The first week of the year is the week that contains that year's first Thursday (='First 4-day week'). The highest week number in a year is either 52 or 53. This year has 52 weeks.This is not the only week numbering system in the world, other systems use weeks starting on Sunday (US) or Saturday (Islamic).

更多详情:http://www.epochconverter.com/weeknumbers

Apple确实支持这一点,因此您可以找到https://developer.apple.com/library/mac/documentation/Cocoa/Reference/Foundation/Classes/NSCalendar_Class/

引用的正确方法

例如,使用ISO-8601 standard

NSCalendar *ISO8601 = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierISO8601];

希望这可以提供帮助。