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

13

I'm having trouble with date , it takes my computer clock time and I wanted it to really get the right time.

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

date_default_timezone_set('America/Sao_Paulo');
$date = date('Y-m-d H:i');
echo $date;
    
asked by anonymous 13.03.2014 / 20:28

5 answers

9

You can get the date and time from a server NTP . Here is 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 full, more accurate code you can find here: link

    
13.03.2014 / 23:07
3

PHP takes the time of the server on which apache is running. It is probably the same as your computer's 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.

    
13.03.2014 / 20:40
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 a server out there, type what hosts your personal website, you can do a script there at to get the date / time from there. In this case, the local script would have to make a cross domain request - between domains, that is, between servers. Like, what time is it there? But I confess I've never done this, I'd rather set the clock on my PC, anyway, follow the link if you're interested: Client URL .

    
13.03.2014 / 20:52
1

It can be used in this way, the database does not change and the advantage is that it does not need the conversion of 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'
";
?> 
    
08.04.2016 / 16:23
0

Put this at the beginning of the document:

date_default_timezone_set('America/Sao_Paulo');

It worked here, but only at the beginning of the document.

    
01.07.2017 / 17:50