2019-01-11 15:44
浏览 36

使用DateTime diff格式化问题

I am trying to find the difference in days between two dates using DateTime. I understand that there are several other posts explaining how to do this. However, I receive an error when my code is run. I think this may be a formatting issue but I am at a loss.

As you can see I have tried to format $orderdate to the Y-m-d format recommended in the docs. It seems to be doing the trick. Am I missing something? According to the docs this should be working.

$orderdate = strip_tags(str_replace(array('"', "'"), "", str_replace(array("
", ""), ' ', $_POST['pickupship-date'])));
$orderdate = $conn->real_escape_string($orderdate);
$orderdate = date( "Y-m-d", strtotime($orderdate) );
echo $orderdate;

$completiondate = date("m/d/Y");
$completiondate = date( "Y-m-d", strtotime($completiondate) );
echo $completiondate;

$duration = $orderdate->diff($completiondate);
$duration->format('%R%a days');
echo $duration;

EDIT: I have updated the code based on suggestions I have received. echo $orderdate and echo $completiondate are outputting exactly as expected. However, I get nothing for $duration.

  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

3条回答 默认 最新

  • douyi02577 2019-01-11 17:45

    It's not clear what do you want to achieve with this code. Most of what it does is incorrect or not needed.

    $orderdate = strip_tags(str_replace(array('"', "'"), "", str_replace(array("
    ", ""), ' ', $_POST['pickupship-date'])));

    You should impose a fixed format for the pickupship-date field. Something like Y-m-d (or m/d/Y if you prefer it more) and stick with it. It doesn't make any sense to have quotes, apostrophes, newlines or HTML tags in a date-time field. If the input value doesn't match the expected format then display an error and stop the processing here.

    $orderdate = $conn->real_escape_string($orderdate);

    Use a DB string escaping function only with the data you use to build an SQL query. This operation does not make any sense for the operations you do below with $orderdate.
    You should use prepared SQL queries to protect the application from SQL injection, not arbitrary escaping and query building by joining strings, anyway.

    $completiondate = date("m/d/Y");
    $completiondate = date( "Y-m-d", strtotime($completiondate) );

    date("m/d/Y") formats the current date & time as string using the m/d/Y format.
    strtotime($completionDate) does the reverse; it tries to parse the just-generated string back into the current time and returns number (the number of seconds since 1970-01-01 00:00:00 UTC).

    Then, date("Y-m-d", ...) produces another text representation of the just-parsed date & time. All in all, these two lines do the same as $completiondate = date('Y-m-d');

    $duration = $orderdate->diff($completiondate);

    This is completely wrong. $orderdate is a string, it does not have the diff() method (it does not have any method, a string is not an object in PHP).
    More, DateTime::diff() expects another DateTime object as argument.

    $duration->format('%R%a days');

    This line is correct (but it works only if $duration is properly created and this doesn't happen now).

    How your code should look like.

    Because it's 2019 and not 2009, you should stay away from the old date & time functions (they don't know how to handle the timezones and they are awkward anyway) and use only the DateTime class (and its friends).

    The code you need could look like this:

    // The timezone
    $tz = new DateTimeZone('America/Chicago');
    // Parse the input value, get a DateTime object back, or FALSE on error
    $orderDate = date_create($_POST['pickupship-date'], $tz);
    if (! $orderDate) {
      // The input value does not look like a valid date
      // Display an error, stop the processing here
      // ...
    // Get the current date & time
    $processingDate = new DateTime('now', $tz);
    // Compute the difference
    $duration = $orderdate->diff($completionDate);
    // Format the difference for display
    $duration->format('%R%a days')


    The call:

    date_create($_POST['pickupship-date'], $tz)

    is almost the same as:

    new DateTime($_POST['pickupship-date'], $tz)

    but it returns FALSE if the input value is not valid.
    There is no way to get a value that signals an invalid input using new.

    The code looks cleaner when you use new DateTime() but it works as expected only if you have already validated (by other means) the value you pass to it. If the input string is not a valid date, the new DateTime object is initialized with 1970-01-01 00:00:00 or with another value you don't want/expect.

    date_create() prevents this by returning FALSE when the input string is not a valid date & time.

    Both ways accept multiple formats for the argument, including partial date & time representations and almost any English textual datetime description (f.e. 'yesterday noon').

    If you want to use a fixed format for the input string you can use DateTime::createFromFormat().
    It uses an additional parameter (the first one) that is a format string (in the format accepted by date() or DateTime::format()) and returns a DateTime object only if the input string matches the provided format (and FALSE otherwise).

    打赏 评论
  • douduan5086 2019-01-11 17:33

    This is the code that ended up working for me:

    $orderdate = strip_tags(str_replace(array('"', "'"), "", str_replace(array("
    ", ""), ' ', $_POST['pickupship-date'])));
    $orderdate = $conn->real_escape_string($orderdate);
    $completiondate = new DateTime('now', new DateTimeZone('America/Chicago'));
    $completiondate = $completiondate->format('Y-m-d');
    $orderdate = new DateTime($orderdate);
    $completiondate = new DateTime($completiondate);
    $duration = $orderdate->diff($completiondate);
    $duration = $duration->format('%R%a days');
    打赏 评论
  • douqiao3930 2019-01-11 17:51

    Make your life simple and use the DateTime Class which will do a lot of things for you. important: the date() function returns a string, not some Date Object. So

    $orderdate = date( "Y-m-d", strtotime($orderdate) );

    diffs strings and not the thing you want.

    $_POST['pickupship-date'] = "2018-03-04";
    $replaceNewLines = str_replace(array("
    ", ""), ' ', $_POST['pickupship-date']);
    //not necessary when you use prepared statements. Always use prepared statements!!!
    // $replaceQuotes = str_replace(array('"', "'"), "", $replaceNewLines);
    $orderdate = strip_tags($replaceNewLines);
    //always use prepared statements, then you don't have to do this
    //$orderdate = $conn->real_escape_string($orderdate);
    // strtotime not necessary $orderdate = date( "Y-m-d ", strtotime($orderdate) );
    $orderdate = new DateTime($orderdate);
    echo '$orderdate :';
    $completiondate = new DateTime();
    echo '$completiondate :';
    var_dump( $completiondate->format("Y-m-d"));
    $duration = $orderdate->diff($completiondate);
    echo '$duration :';
    var_dump($duration->format('%d days'));
    打赏 评论

相关推荐 更多相似问题