How to get the current date and time without using the computer clock?

Asked

Viewed 141,242 times

14

I’m having trouble in the date, he takes my clock from my computer and I wanted him to actually pick the right time.

The result of the following code is that the date will take from your host server.

<?php
date_default_timezone_set('America/Sao_Paulo');
$date = date('Y-m-d H:i');
echo $date;
?>

5 answers

10

You can get the date and time from a server NTP. Follow an example of PHP code that does this:

<?php
$socket = fsockopen('udp://pool.ntp.br', 123, $err_no, $err_str, 1);
if ($socket)
{
    if (fwrite($socket, chr(bindec('00'.sprintf('%03d', decbin(3)).'011')).str_repeat(chr(0x0), 39).pack('N', time()).pack("N", 0)))
    {
        stream_set_timeout($socket, 1);
        $unpack0 = unpack("N12", fread($socket, 48));
        echo date('Y-m-d H:i:s', $unpack0[7]);
    }

    fclose($socket);
}

The complete and most accurate code you can find here: http://xlo.co/blog/general/php-ntp-client

4

PHP takes the time from the server apache is running on. It is probably the same as your computer clock because it is running on a local server, but when the same script is run on a hosted server, it will return the time of this server.

1

Put this at the beginning of the document:

date_default_timezone_set('America/Sao_Paulo');

Here it worked, but only at the beginning of the document.

1

You can use this way, the database does not change and the advantage is that it does not need the conversion from date en-US to date pt-BR, it is already automatic

<?php
$matricula = date ("Y-m-d");
echo"<input type='date' value='$matricula' name='date'
";
?> 

1

You can set the date and time using functions such as date_date_set.

However, you will need a source for this information. If you have any servers out there, like the one that hosts your personal website, you can make a script there at to get the date/time from there. In this case, the local script would have to make a request cross Domain - between domains, that is, between servers. Type: do you have hours there? But I confess that I never did it, I prefer to fix the clock of my PC, anyway, follow the link if you are interested: Client URL.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.