Micha
Micha

Reputation: 383

PHP using date() function to get numeric value for Sunday - Saturday

I am trying to get a numeric value (0-6) for the last day of the week in the month however it keeps returning a value of 3 when it in fact should be 4 for the month of 05-2018. Am I going about this in the wrong manner?

$endMonth = date('Y-m-t');
$dayPostition = date('w', $endMonth);

Upvotes: 0

Views: 83

Answers (4)

Ryan Jeric
Ryan Jeric

Reputation: 380

If you want to get the last day of month, you can use cal_days_in_month()

This function will return the number of days in the month of year for the specified calendar." http://php.net/manual/en/function.cal-days-in-month.

Try this

$getlastday = cal_days_in_month(CAL_GREGORIAN, 05, 2018);
$endMonth = date('2018-05-'.$getlastday);
$dayPostition = date('w', strtotime($endMonth));

Upvotes: 1

lalengua
lalengua

Reputation: 529

You are sending a string, not a date... try this

$endMonth = date('Y-m-t');
$dayPostition = date('w', strtotime($endMonth));

Upvotes: 1

Obsidian Age
Obsidian Age

Reputation: 42304

The problem is that the second parameter of date() must be a timestamp rather than a string, and date() itself simply returns a string.

As such, you need to explicitly convert the first date() to a timestamp with strtotime():

$testvar = date('Y-m-t');
$lastDay = date('w', strtotime($testvar));

Which can be seen working here.

Upvotes: 2

Eddie
Eddie

Reputation: 26844

If you want to get the last on current month, you can:

$date = new DateTime("now");
$date->modify('last day of this month');
echo $date->format('w');

Or using a specific date

$date = new DateTime("2018-05-01"); //May 1, 2018
$date->modify('last day of this month');
echo $date->format('w');

Upvotes: 2

Related Questions