testing
testing

Reputation: 20279

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(@"week: %@", weeknumber);

Taken from http://iosdevelopertips.com/cocoa/date-formatter-examples.html

Where do I find the allowed date formats?

Upvotes: 3

Views: 4024

Answers (5)

Nghia Luong
Nghia Luong

Reputation: 790

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.

Upvotes: 0

Uli2000
Uli2000

Reputation: 11

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);

Upvotes: 1

Marco
Marco

Reputation: 340

Or use:

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

The numbering follows the ISO 8601 definition of week.

Upvotes: 1

Elfred
Elfred

Reputation: 3851

Use an NSCalendar and NSDateComponents.

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

Upvotes: 5

Max Seelemann
Max Seelemann

Reputation: 9364

You should user NSDateFormatter like so:

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

Upvotes: 0

Related Questions