doulongdan2264 2019-01-11 15:44
浏览 40
已采纳

使用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;

date_default_timezone_set('America/Chicago');
$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')
    

    Remarks

    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).

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥20 ML307A在使用AT命令连接EMQX平台的MQTT时被拒绝
  • ¥20 腾讯企业邮箱邮件可以恢复么
  • ¥15 有人知道怎么将自己的迁移策略布到edgecloudsim上使用吗?
  • ¥15 错误 LNK2001 无法解析的外部符号
  • ¥50 安装pyaudiokits失败
  • ¥15 计组这些题应该咋做呀
  • ¥60 更换迈创SOL6M4AE卡的时候,驱动要重新装才能使用,怎么解决?
  • ¥15 让node服务器有自动加载文件的功能
  • ¥15 jmeter脚本回放有的是对的有的是错的
  • ¥15 r语言蛋白组学相关问题