TalG TalG - 4 months ago 16
MySQL Question

Getting the local date, time and microseconds of the server

I'm using this function it was suggested in some post here on this site (i don't remember where anymore)

function udate($format, $utimestamp = null) {
if (is_null($utimestamp))
$utimestamp = microtime(true);

$timestamp = floor($utimestamp);
$microseconds = round(($utimestamp - $timestamp) * 1000000);

return date(preg_replace('`(?<!\\\\)u`', $microseconds, $format), $timestamp);

After searching and experimenting a lot with the code, I wanted to get the date,time and the microseconds of the server so I can write it into my MySql database and this was the only solution that worked for me.

The only Problem is that I'm getting the UTC time and not the local time of the server, I've set my server time to local using the
timedatectl set-local-rtc 1
command but it didn't help.

Does any one have an idea, what do I have to change in this function, to get my servers local time?


Have you had a look at the DateTime and DateTimeZone classes?

$date = new \DateTime('now', new \DateTimeZone('[SOURCE TZ]'));
$date->setTimezone(new \DateTimeZone('[DEST TZ]'));
return $date->format('Y-m-d h:i:s.u');

You can set source and destination timezones as above. You may be able to do without the source time zone entirely.

To apply this to your code, you will probably need to do something like

\DateTime::createFromFormat('U.u', microtime(true))