David
David

Reputation: 99

How to properly compare dates to strings in PHP?

I am using two functions to find certain dates relative to the ones i am passing to the function. EX: my function mgeStart($date) takes $date and finds the previous friday (as this is the start of the work week). This function works as it should. The function mgeEnd($date) compares the current date to Thursday. This is where my problem arises. Every date I pass through to mgeEnd() thinks the date I am passing it is thursday (no errors are reported in my error log). My two functions are held in functions.php, here they are:

I have added multiple error_log() statements to determine that every entry goes through the first if statement of mgeEnd().

function mgeStart($date){

  if(date('D', $date) == 'Fri') { // It is friday
    $start = $date;
  }else{
    $start = date('Y-m-d', strtotime('last friday', strtotime($date))); // last friday
  }
  // error_log("Date: ".$date." Start: ".$start);
return $start;
}

function mgeEnd($date){
  if(date('D', $date) == 'Thu') { // It is thurs
     $end = $date;
  }else{
    error_log("enter2");  //THIS NEVER GETS ENTERED
    $end = date('Y-m-d', strtotime('next thursday', strtotime($date))); // last friday
  }
  return $end;
  error_log("Date: ".$date." End: ".$end);
}

I call the functions in document2:

$endDate = mgeEnd($row_3['WorkDate']);
$startDate = mgeStart($row_3['WorkDate']);

These are inside a for loop and the values are unset at the end of each loop.

The expected result of my program is to have mgeEnd() return the next thursday of the date passed to it.

The error log statements in mgeEnd() are never posted to the log, whereas the one in mgeStart() are. mgeStart() behaves as it should whereas mgeEnd() does not.

Upvotes: 0

Views: 47

Answers (1)

miken32
miken32

Reputation: 42705

It always pays to check your error logs. I bet you'd find this in yours:

Notice: A non well formed numeric value encountered...

You can't pass a string to the date() function, it expects a UNIX timestamp. You need to use strtotime() to do the conversion. Try this:

<?php

function mgeStart($date) {
    $date = strtotime($date);
    if(date('D', $date) === 'Fri') { // It is friday
        $start = $date;
    } else {
        $start = date('Y-m-d', strtotime('last friday', $date)); // last friday
    }
    return $start;
}

function mgeEnd($date) {
    $date = strtotime($date);
    if(date('D', $date) === 'Thu') { // It is thurs
        $end = date('Y-m-d', $date);
    } else {
        $end = date('Y-m-d', strtotime('next thursday', $date)); // next thursday
    }
    return $end;
}

echo mgeEnd("2019-05-17");

Live demo: https://3v4l.org/EVnmt

Upvotes: 2

Related Questions