7

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?

Peter
  • 8,776
  • 6
  • 62
  • 95
Edoardo
  • 599
  • 2
  • 9
  • 26

4 Answers4

11

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

Blinkydamo
  • 1,582
  • 9
  • 20
  • 1
    I think this is the best answer because it's showing how to use `DateTime` before `date`, which is very important for the PHP community evolution. – Machado Aug 07 '19 at 00:07
6

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>";
krasipenkov
  • 2,031
  • 1
  • 11
  • 13
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

Peter
  • 8,776
  • 6
  • 62
  • 95
-1

You almost have it right but not quite. Why are you using strtotime on $number2? Change it to $number2 = date('N', $tomorrow); and it will work.

Chris
  • 5,571
  • 2
  • 20
  • 32