How can I get the user's local time instead of the server's time?

How can I get the time of the client side? When I use date() it returns server's time.

Answers:

Answer

As mentioned by everyone PHP only displays server side time.

For client side, you would need Javascript, something like the following should do the trick.

var currentTime = new Date();
var hours = currentTime.getHours();
var minutes = currentTime.getMinutes();

if (minutes < 10) {
    minutes = "0" + minutes;
}

document.write("<b>" + hours + ":" + minutes + " " + "</b>");

And if you want the AM/PM suffix, something like the following should work:

var currentTime = new Date();
var hours = currentTime.getHours();
var minutes = currentTime.getMinutes();

var suffix = "AM";

if (hours >= 12) {
    suffix = "PM";
    hours = hours - 12;
}

if (hours == 0) {
    hours = 12;
}

if (minutes < 10) {
    minutes = "0" + minutes;
}

document.write("<b>" + hours + ":" + minutes + " " + suffix + "</b>");

Here is a list of additional JavaScript Date and Time functions you could mess around with.

Answer

Here's a "PHP" solution:

echo '<script type="text/javascript">
var x = new Date()
document.write(x)
</script>';
Answer

As PHP runs on the server-side, you cannot access the client-side time from PHP : PHP doesn't know much about the browser -- and you can have PHP scripts that run without being called from a browser.

But you could get it from Javascript (which is executed on the client-side), and, then, pass it to PHP via an Ajax request, for example.


And here are a couple of questions+answers that might help you getting started :

Answer

PHP is server side only as far as i know.

You maybe want to use JavaScript.

Answer

You could possibly use Geolocation by IP Address to work out which country the user is in, and then use that.

But using Javascript or letting the user choose a Timezone will probably be better.

Answer

As other's have mentioned, you can use Geo Location Services based on the IP Address.

I found it to be off by about 18 seconds due to IP location accuracy, by using a $responseTime offset it helped me narrow it down to 2 second accuracy in the Viewers Location.

  <?php; 

   echo deviceTime('D, M d Y h:i:s a');

   function deviceTime($dateFormatString)
   { 
        $responseTime = 21;
        $ip = (isset($_SERVER["HTTP_CF_CONNECTING_IP"])?$_SERVER["HTTP_CF_CONNECTING_IP"]:$_SERVER['REMOTE_ADDR']);
        $ch = file_get_contents('https://ipapi.co/'.$viewersIP.'/json/');
        $ipParts = json_decode($ch,true);
        $timezone = $ipParts['timezone'];
        $date = new DateTime(date('m/d/Y h:i:s a', time()+$responseTime));
        $date->setTimezone(new DateTimeZone($timezone));
    return $date->format($dateFormatString);
   }
   ?>

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us Javascript

©2020 All rights reserved.