Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

javascript

php

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

like image 826
Simon Avatar asked Apr 24 '10 15:04

Simon


3 Answers

Here's a "PHP" solution:

echo '<script type="text/javascript">
var x = new Date()
document.write(x)
</script>';
like image 199
phimuemue Avatar answered Nov 18 '22 19:11

phimuemue


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.

like image 21
Russell Dias Avatar answered Nov 18 '22 19:11

Russell Dias


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.

like image 4
Jamescun Avatar answered Nov 18 '22 20:11

Jamescun