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:
Objective C
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
<?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
.