1

I want to create a new datetime variable from a string variable using datetime function.
So, I have:
$sqlData=$day . "." . $month . "." . $year;
echo $sqlData;

$local=new datetime('${sqlData}');
echo $local;

The problem appear on echo $local;

Error msg: Failed to parse time string (${sqlData}), unexpected character'

BOB
  • 700
  • 2
  • 16
  • 35

2 Answers2

4

Why do you think you need the { and ' in DateTime?
$sqlData is a string, and DateTime wants a string. So why not just give it the string?

$sqlData=$day . "." . $month . "." . $year;
echo $sqlData;

$local=new datetime($sqlData);
var_dump($local);

Then echo won't work since it's an object, so var_dump/print_r or var_export

https://3v4l.org/nq8iY

To echo the string you need to format the object.

echo $local->format('Y-m-d');
Andreas
  • 23,610
  • 6
  • 30
  • 62
2

This below worked for me, you need to set the format and return it as a new variable.

   <?php
    $date = 05; $month = 05; $year = 1990;
    $sqlData="$date.$month.$year";
    $local=new datetime($sqlData);
    $date = $local->format('Y/m/d');
    echo $date;
WKoppel
  • 504
  • 3
  • 15