calculate calendar week
how can I calculate the calendar week? A year has 52/53 weeks and there are two rules:
-USA
-DIN 1355 / ISO 8601
I'd like to work with DIN 1355 / ISO 8601. How can I manage that?
Edit:
NSDate *today = [NSDate date];
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:@"ww"];
NSString *weeknumber = [dateFormat stringFromDate: today];
NSLog(@"wee开发者_Go百科k: %@", weeknumber);
Taken from http://iosdevelopertips.com/cocoa/date-formatter-examples.html
Where do I find the allowed date formats?
Use an NSCalendar
and NSDateComponents
.
NSCalendar *cal = [NSCalendar currentCalendar];
NSDateComponents *components = [cal components:NSWeekCalendarUnit fromDate:date];
NSInteger week = [components week];
Or use:
CFAbsoluteTime currentTime = CFAbsoluteTimeGetCurrent();
CFTimeZoneRef currentTimeZone = CFTimeZoneCopyDefault();
SInt32 weekNumber = CFAbsoluteTimeGetWeekOfYear(currentTime, currentTimeZone);
The numbering follows the ISO 8601 definition of week.
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);
You should user NSDateFormatter
like so:
NSDateFormatter *fm = [[NSDateFormatter alloc] initWithDateFormat:@"ww" allowNaturalLanguage:NO];
NSString *week = [fm stringFromDate: date];
There is many kinds of 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).
More details: http://www.epochconverter.com/weeknumbers
And Apple does support that, so you could find correct way referred from https://developer.apple.com/library/mac/documentation/Cocoa/Reference/Foundation/Classes/NSCalendar_Class/
For example, with ISO-8601 standard
:
NSCalendar *ISO8601 = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierISO8601];
Hope this could help.
精彩评论