user1358298
user1358298

Reputation:

PHP DateTime - Make from YEAR, WEEK and WEEKDAY

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

Answers (2)

vascowhite
vascowhite

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);

http://3v4l.org/EVqHj

Upvotes: 4

user1358298
user1358298

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

Related Questions