@@ -5,7 +5,7 @@ static const int YEARS100 = 36524;
55static const int YEARS4 = 1461 ;
66static const int YEARS1 = 365 ;
77
8- typedef enum { YDAY , WDAY , MDAY , WEEK , MONTH , QUARTER , YEAR , YEARMON , YEARQTR } datetype ;
8+ typedef enum { YDAY , WDAY , MDAY , WEEK , ISOWEEK , ISOYEAR , MONTH , QUARTER , YEAR , YEARMON , YEARQTR } datetype ;
99
1010static inline bool isLeapYear (int year ) {
1111 return (year % 100 != 0 || year % 400 == 0 ) && year % 4 == 0 ;
@@ -29,6 +29,22 @@ void convertSingleDate(int x, datetype type, void *out)
2929 return ;
3030 }
3131
32+ if (type == ISOWEEK || type == ISOYEAR ) {
33+ // ISO 8601-conformant week, as described at https://en.wikipedia.org/wiki/ISO_week_date
34+ // The ISO week and year are those of the nearest Thursday
35+ // Thursdays are multiples of 7, since x=0 (1970-01-01) was a Thursday
36+ int thu = x + (3 - (x % 7 + 10 ) % 7 );
37+ int res ;
38+ if (type == ISOWEEK ) {
39+ convertSingleDate (thu , YDAY , & res );
40+ res = (res - 1 ) / 7 + 1 ;
41+ } else {
42+ convertSingleDate (thu , YEAR , & res );
43+ }
44+ * (int * )out = res ;
45+ return ;
46+ }
47+
3248 int days = x - 11017 ;
3349
3450 int years400 = days / YEARS400 ;
@@ -134,6 +150,8 @@ SEXP convertDate(SEXP x, SEXP type)
134150 else if (!strcmp (ctype_str , "wday" )) ctype = WDAY ;
135151 else if (!strcmp (ctype_str , "mday" )) ctype = MDAY ;
136152 else if (!strcmp (ctype_str , "week" )) ctype = WEEK ;
153+ else if (!strcmp (ctype_str , "isoweek" )) ctype = ISOWEEK ;
154+ else if (!strcmp (ctype_str , "isoyear" )) ctype = ISOYEAR ;
137155 else if (!strcmp (ctype_str , "month" )) ctype = MONTH ;
138156 else if (!strcmp (ctype_str , "quarter" )) ctype = QUARTER ;
139157 else if (!strcmp (ctype_str , "year" )) ctype = YEAR ;
0 commit comments