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

报告相同问题?

悬赏问题

  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测
  • ¥15 ETLCloud 处理json多层级问题
  • ¥15 matlab中使用gurobi时报错
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭
  • ¥15 2020长安杯与连接网探
  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么