Home > Enterprise >  php8.1 - Deprecated Functionality: DateTime()
php8.1 - Deprecated Functionality: DateTime()

Time:09-20

We use the following code that worked perfectly on php7.4, but we get a deprecated error on php8.1. But how can we succesfully rewrite this for php8.1?

Error:

Deprecated Functionality: DateTime::__construct(): Passing null to parameter #1 ($datetime) of type string is deprecated

Current code:

$today = new \DateTime();$orderdate = new \DateTime($orders->getCreatedAt());

<?php if($orderdate->diff($today)->days > 14):?>

<?php endif;?>

CodePudding user response:

You can no longer do this:

new \DateTime(null);

In your exact use case, I think that PHP has highlighted a bug in your code. If the order does not have a created at date, you'll populate the variable with the date/time when the script runs, which may not be what you want:

var_dump(new \DateTime('1985-12-31 15:00:00'));
var_dump(new \DateTime(''));
var_dump(new \DateTime(null));
object(DateTime)#1 (3) {
  ["date"]=>
  string(26) "1985-12-31 15:00:00.000000"
  ["timezone_type"]=>
  int(3)
  ["timezone"]=>
  string(16) "Europe/Amsterdam"
}
object(DateTime)#1 (3) {
  ["date"]=>
  string(26) "2022-09-19 12:28:23.003960"
  ["timezone_type"]=>
  int(3)
  ["timezone"]=>
  string(16) "Europe/Amsterdam"
}

Deprecated: DateTime::__construct(): Passing null to parameter #1 ($datetime) of type string is deprecated in /in/67OFM on line 5
object(DateTime)#1 (3) {
  ["date"]=>
  string(26) "2022-09-19 12:28:23.003987"
  ["timezone_type"]=>
  int(3)
  ["timezone"]=>
  string(16) "Europe/Amsterdam"
}

Demo

If you want to use DB information:

$orderdate = $orders->getCreatedAt()
    ? new \DateTime($orders->getCreatedAt())
    : null;

If you want to default to "now", make it explicit so nobody wonders whether it's intentional:

$orderdate = $orders->getCreatedAt()
    ? new \DateTime($orders->getCreatedAt())
    : new \DateTime();

Last but not least... Analyse if it makes sense from the business logic standpoint to have orders with no creation date. What does that mean?

  • Related