Reputation:
I have the year, week, and weekday stored as integers. Weekdays are 0 based, starting with Monday. The variables are equivalent to YEAR(date), WEEK(date) and WEEKDAY(date, 1) functions in MySQL. For example for today (Thursday 30th Oct 2014) it would be:
$year = 2014;
$week = 44;
$weekday = 3; // Thursday
Using these variables how do I set the date of a DateTime object?
I tried using:
DateTime::createFromFormat("Y-z", $year . "-" . ((($week - 1) * 7) + $weekday));
And a few other variations, but nothing gave me the expected results.
Any ideas?
Upvotes: 5
Views: 1319
Reputation: 18440
It looks to me as if you need to use \DateTime::setISODate()
. However, you will need to add 1 to the weekday as Monday is 1.
$date = (new \DateTime())->setISODate($year, $week, $weekday + 1);
var_dump($date);
Upvotes: 4
Reputation:
This solution:
$year = 2014;
$week = 44;
$weekday = 3; // Thursday
$day_in_question = new DateTime();
$day_in_question->setTime(0, 0, 0);
$day_in_question->setISODate($year, $week_number, $weekday + 1);
Seems to give the expected result
Hope it helps someone
Upvotes: 4