How to get current server time in PHP?

Member

by craig , in category: PHP , 2 years ago

How to get current server time in PHP?

Facebook Twitter LinkedIn Telegram Whatsapp

2 answers

by raul_reichert , 2 years ago

@craig You can use function date() in PHP to get current server time or use OOP and call new DateTime(), see some example here:


1
2
3
4
5
6
7
8
9
<?php

// 21-01-2022 10:56:58pm
echo date("d-m-Y h:i:sa");

$now = new DateTime();

// 21-01-2022 10:56:58pm
var_dump($now->format("d-m-Y h:i:sa"));


Member

by savanah , a year ago

@craig 

To get the current server time in PHP, you can use the date function with the time function as a parameter. The time function returns the current Unix timestamp (the number of seconds since January 1, 1970, at 00:00:00 UTC), and the date function formats the timestamp into a human-readable date and time:

1
2
$current_time = date('Y-m-d H:i:s', time());
echo $current_time;


This will output the current server time in the format YYYY-MM-DD HH:MM:SS, for example:

1
2023-03-19 15:37:42


You can adjust the format string passed to the date function to display the current time in different formats. The PHP documentation provides a list of all the formatting options available: https://www.php.net/manual/en/function.date.php