Getting the Date and numeric weekday in PHP

22,838

Solution 1

You have little error in the code, here`s the working one:

$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', $tomorrow);
echo "Tomorrow: " . date('Y-m-d', $tomorrow) . " weekday: " . $number2 . "<br>";

Solution 2

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

Solution 3

DateTime is the Object Oriented method of working with dates in PHP. I find it to be working much more fluently. That aside, it looks alot better.

// Create a new instance
$now = new DateTime();
echo $now->format('N');

// Next day
$now->modify('+1 day');
echo $now->format('N');

Resources

Share:
22,838
Edoardo
Author by

Edoardo

Updated on July 05, 2022

Comments

  • Edoardo
    Edoardo almost 2 years

    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?