Calculate calendar week

How can I calculate a calendar week? A year has 52/53 weeks and there are two rules:

-USA

-DIN 1355 / ISO 8601

I would like to work with DIN 1355 / ISO 8601. How do I do this?

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 can I find the allowed date formats?

+3
source share
5 answers

Use NSCalendarand NSDateComponents.

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

Or use:

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

The numbering complies with the week definition of ISO 8601.

+1
source
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);
+1

NSDateFormatter :

NSDateFormatter *fm = [[NSDateFormatter alloc] initWithDateFormat:@"ww" allowNaturalLanguage:NO];
NSString *week = [fm stringFromDate: date];
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 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

And Apple really supports this, so you can find the correct path 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 helps.

0
source

Source: https://habr.com/ru/post/1762653/


All Articles