简体   繁体   中英

PHP date returns wrong number of days left to next monday

Im trying to calculate number of days left to next monday and it returns 10, Im sure its wrong, days left to next monday is 5, what im doing wrong?

 if (isset($_POST['entry'])) {


  $email=mysql_real_escape_string($_POST['email']);
  $t_shirt=mysql_real_escape_string($_POST['t-shirt']);
  $today = date("m.d.Y");
  $next_monday = date("d, m, Y", strtotime('next monday'));
  $last_monday = date("d, m, Y", strtotime('last monday'));
  $today = date("d.m.Y");


  $select_current=mysql_query("SELECT * FROM entry_form WHERE email='$email'");
   if (mysql_num_rows($select_current) >= 1) {
   while ($row=mysql_fetch_array($select_current)) {

    $last_registered=$row['registered'];

    } 

    $diff = abs(strtotime($last_registered) - strtotime($last_monday));
    $years = floor($diff / (365*60*60*24));
    $months = floor(($diff - $years * 365*60*60*24) / (30*60*60*24));
    $days = floor(($diff - $years * 365*60*60*24 - $months*30*60*60*24)/ (60*60*24));

    echo "$days";

     }

You making it to difficult for your self, already asked that question on calculating date_diff:

 //get today's timestamp
 $date_now = date_create("today");

 //get next monday date
 $mon_date = date_create("next monday");

 //calculate date difference
 $difference = date_diff($mon_date,$date_now);

 $int = intval($difference->format('%a'));
 echo $int;

You can use DateTime and DateInterval objects like this:

$d = new DateTime('today');
$lm = new DateTime('last monday');
$nm = new DateTime('next monday');

echo $d->diff($lm)->format("%R%a"); // output -3
echo $d->diff($nm)->format("%R%a"); // output +4

This is essentially the object oriented version of bart's answer . The %R in the format specifier gives the + or - and the %a gives the number of days.

There's a much simpler way to figure out how many days to the next Monday: use date('N') .

  • N : ISO-8601 numeric representation of the day of the week (added in PHP 5.1.0)
    1 (for Monday) through 7 (for Sunday)

http://php.net/date

$daysTillNextMonday = 7 - (date('N') - 1);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM