When using MySQL you can print the current date and time using the NOW()
function. But how can you do this using PHP? When using PHP, we can use the date()
function instead. Let's explore how it works and how we achieve the same result as MySQL's NOW()
function in PHP.
NOW() function in PHP
The NOW() function in MySQL by default returns the server's current date time in a year, month, day, hour, minute, and second format (YYYY-MM-DD HH:MM:SS). We can achieve the same result using PHP, in the same format but using PHP's native date time function, date()
. We can use this by providing the following format.
PHP now format
Y-m-d H:i:s
echo date("Y-m-d H:i:s");
There isn't a function in PHP called NOW()
, and calling this function will trigger a PHP fatal error. If that happens be sure to replace it with the PHP NOW()
solution above.
Fatal error: Uncaught Error: Call to undefined function NOW()
You can modify the format of the date and time by amending the string format to provide the date function as well as learning more about getting the current date and time in PHP.
Laravel date now
If you're using Laravel and looking to get the current date similar to now, you can use Cabon.
use Illuminate\Support\Carbon;
$currentDateTime = Carbon::now();
To produce the same date time format as our date function, you can pass the format method to Carbon.
$currentDateTimeFormatted = Carbon::now()->format('Y-m-d H:i:s');