Maciek
Maciek

Reputation: 1982

PHP First day of month using DateTime

I have a datetime in php:

$datetime=new DateTime();

How can I get day of week:

$datetime->format("w");

But for first day of current $datetime month?

Upvotes: 3

Views: 6095

Answers (2)

Murad Hasan
Murad Hasan

Reputation: 9583

You can try with this:

Requires PHP 5.3 to work ("first day of" is introduced in PHP 5.3).

Otherwise the example above is the only way to do it:

l = A full textual representation of the day of the week

$datetime = new DateTime();
$datetime->modify('first day of this month');
echo $output = $datetime->format("l"); //Sunday

Alternative:

echo date("l", strtotime(date('Y-m-01'))); //Sunday

Upvotes: 0

Kevin
Kevin

Reputation: 41885

Just use the ->modify() method to adjust accordingly:

$datetime = new DateTime();
$datetime->modify('first day of this month');
$output = $datetime->format("w");
echo $output; // 0 - sunday

Without the relative date time string:

$dt = new DateTime();
$dt->setDate($dt->format('Y'), $dt->format('m'), 1);
$output = $dt->format('w');
echo $output;

Upvotes: 10

Related Questions