How can DateObject handle calender weeks
Note This answer exposed a bug in DateList
's handling of the "Week"
(or "WeekShort"
) element for week one when it begins in the previous year. This was spotted by @ChrisDegnen (see the comments) and has been acknowledged by Wolfram who suggested the workaround.
I don't believe DateObject
has a concept of a week as a period of time in the same way that it seems to for a year, month or day, so I think the best you can do is a DateObject
for the first day of the week.
And since the DateFormat
option for DateObject
is the display format rather than an interpretation format we use DateList
to do the conversion...
fromYearWeek[{y_Integer, w_Integer}] :=
DateObject[
DatePlus[DateList[{ToString[y] <> "-" <> ToString[w], {"Year",
"Week"}}], 1], DateFormat -> {"ISOWeekDate"}]
fromYearWeek[{y_Integer, 1}] :=
DateObject[
DatePlus[DateList[{ToString[y] <> "-2", {"Year",
"Week"}}], -6], DateFormat -> {"ISOWeekDate"}]
Note that I have added a day to convert to ISO weeks which begin on a Monday and changed the DateObject
display format to indicate the week number.
It includes a special case for week one - calculating the date list for week two and subtracting 6 days.
You could use DateList
to work out the date. For example, (naïvely assuming week 1 begins on January 1st).
{year, week} = {2014, 26};
date = DateList[{year, 1, (week - 1)*7 + 1}]
{2014, 6, 25, 0, 0, 0.}
For example:
dates = {{2014, 2}, {2014, 8}, {2014, 16}, {2014, 26}};
values = {4, 6, 3, 8};
newdates = DateList[{#1, 1, (#2 - 1)*7 + 1}] & @@@ dates;
DateListPlot[Transpose[{newdates, values}]]
Edit
Using ISO weeks and adjusting accordingly. (ISO week is taken to be "the week with the year's first Thursday in it ", so week 1 of 2014 begins on December 30th 2013.)
isodate[{year_, week_}] := Module[{isoAdjust },
isoAdjust = Cases[Map[{#, DateString[{year, 1, #},
"DayNameShort"]} &, Range[7]], {_, "Thu"}][[1, 1]] - 3;
DateList[{year, 1, (week - 1)*7 + isoAdjust}]]
isodate[{2014, 1}]
{2013, 12, 30, 0, 0, 0.}
isodate[{2014, 26}]
{2014, 6, 23, 0, 0, 0.}
newdates = isodate /@ dates;
DateListPlot[Transpose[{newdates, values}]]