Reputation: 24886
In Objective C, how do I take the GMT/UTC date and apply the ISO-8601 rule to get the week number?
PHP generates a week number of the year in ISO-8601 format when one uses the gmdate('W')
statement. This, however, doesn't match in Objective C when you try to just take the GMT/UTC date and get the week number because it doesn't do it in the ISO-8601 way. Here's what the PHP documentation says about ISO-8601 with the 'W'
parameter:
"
W
: ISO-8601 week number of year, weeks starting on Monday" [emphasis mine]
So, when I look at my calendar for 2016, Jan 26 falls on week 05 if I disregard that "starting on Monday" rule, and falls on 04 if I take that rule into consideration.
Compare these two examples, one in PHP, the other in Objective C, and you'll get two different results:
NSCalendar *calender = [NSCalendar currentCalendar];
NSDateComponents *dateComponent = [calender components:(NSWeekOfYearCalendarUnit | NSDayCalendarUnit | NSMonthCalendarUnit | NSYearCalendarUnit) fromDate:[NSDate date]];
NSString *sWeekNum = [NSString stringWithFormat:@"%ld",(long)dateComponent.weekOfYear];
if ([sWeekNum length] < 2) {
sWeekNum = [NSString stringWithFormat:@"0%ld",(long)dateComponent.weekOfYear];
}
NSLog(@"%@",sWeekNum);
<?php
error_reporting(E_ALL);
ini_set('display_errors','On');
// SET OUR TIMEZONE STUFF
try {
$sTimeZone = 'GMT';
if (function_exists('date_default_timezone_set')) {
date_default_timezone_set($sTimeZone);
} else {
putenv('TZ=' .$sTimeZone);
}
ini_set('date.timezone', $sTimeZone);
} catch(Exception $e) {}
echo gmdate('W') . "\n";
For instance, today is Jan 26, 2016 @ 1:48am EST for me. The Objective C emits 05
, while the PHP emits 04
.
Upvotes: 0
Views: 396
Reputation: 285082
NSCalendar
can be initialized as ISO8601
calendar.
NSCalendar *calender = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierISO8601];
unsigned int weekOfYear = (unsigned int)[calender component:NSCalendarUnitWeekOfYear fromDate: [NSDate date]];
NSString *sWeekNum = [NSString stringWithFormat:@"%02u",weekOfYear];
NSLog(@"%@", sWeekNum);
Upvotes: 2
Reputation: 24886
I couldn't figure out the solution in Objective C completely. I had to switch to C/C++ (C in this case), which required that I changed my .m file (where I was building the code) into a .mm file so that I could mix C/C++ with Objective C, and then ensure that this was compiled in the project settings.
#include <string>
#include <time.h>
//...and then, later on in the code...
time_t rawtime;
struct tm *t;
char b[3]; // 2 chars + \0 for C strings
time( &rawtime );
t = gmtime(&rawtime);
strftime(b,3,"%W",t);
NSString *sWeekNum = [NSString stringWithFormat:@"%s",b];
This also ensures it's 2 digits. So, one doesn't have to do that extra step in order to make it match the PHP version.
Upvotes: 0