Reputation: 3105
I've got a year, an ISO-Week and a weekday (year 2015, week 7, weekday 1 == 2015-02-09) and I'd like to convert it to the date.
So I do it the following way:
date <- "2015:7:1"
as.Date(date, format="%Y:%V:%u")
[1] "2015-03-25"
As you can see I get the wrong date (it's today). When using another format-string (%U or %W instead of %V) I get "2015-02-16" as a result -- one week too late because %U and %W count weeks from 0 on.
What am I missing with %V?
Upvotes: 3
Views: 4472
Reputation: 61
I'd like to caution. The suggested way of calculating doesn't always work as it should, for example:
isoyear = c(2015, 2015)
isoweek = c(52, 53)
iyw=paste(isoyear,isoweek,1,sep=":")
as.Date(iyw, format = "%Y:%W:%u") - 7
[1] "2015-12-21" NA
but if we check the isoweek of "2015-12-31", we get the following:
isoweek("2015-12-28")
[1] 53
It's better to use the function ISOweek2date() from ISOweek package instead.
Upvotes: 6
Reputation: 44525
The issue is that you can use %V
for output, but not input. Note in ? strptime
:
%V: Week of the year as decimal number (01–53) as defined in ISO 8601. If the week (starting on Monday) containing 1 January has four or more days in the new year, then it is considered week 1. Otherwise, it is the last week of the previous year, and the next week is week 1. (Accepted but ignored on input.)
So, that means you should probably use %W
and subtract a week:
as.Date("2015:7:1", format = "%Y:%W:%u") - 7
[1] "2015-02-09"
And then note how %V
is allowed on output:
strftime(as.Date("2015:7:1", format = "%Y:%W:%u") - 7, "%Y:%V:%u")
[1] "2015:07:1"
Upvotes: 5