Getting the Date and numeric weekday in PHP

Edoardo picture Edoardo · Nov 11, 2016 · Viewed 17.6k times · Source

i'm developing an application in PHP and I need to use dates and the numeric representation of weekdays.

I've tried the following:

$today = date("Y-m-d");
$number = date('N', strtotime($today));
echo "Today: " . $today . " weekday: " . $number . "<br>";
$today = strtotime($today);
$tomorrow = strtotime($today);
$tomorrow = strtotime("+1 day", $today);
$number2 = date('N', strtotime($tomorrow));
echo "Tomorrow: " . date('Y-m-d', $tomorrow) . " weekday: " . $number2 . "<br>";

Output

Today: 2016-11-11 weekday: 5
Tomorrow: 2016-11-12 weekday: 4

This isn't right because the weekday of tomorrow should be 6 instead of 4.

can someone help me out?

Answer

Blinkydamo picture Blinkydamo · Nov 11, 2016

Using DateTime would provide a simple solution

<?php
$date = new DateTime();
echo 'Today: '.$date->format( 'Y-m-d' ) .' weekday '. $date->format( 'N' )."\n";
$date->modify( '+1 days' );
echo 'Tomorrow: '.$date->format( 'Y-m-d' ) .' weekday '. $date->format( 'N' )."\n";

Output

Today: 2016-11-11 weekday 5
Tomorrow: 2016-11-12 weekday 6

However the day numbers are slightly different, the N respresents the weekday number and as you can see Friday (Today) is shown as 5. With that Monday would be 1 and Sunday would be 7.

If you look at the example below you should get the same result

echo date( 'N' );

Output

5

Date Formatting - http://php.net/manual/en/function.date.php