Reputation: 19
I would like to make a page that greets the user with the classic "good morning/evening", depending on the time of the day. However, I understand that I can't just get the server time because if, say, a user in Japan viewed the page, it might receive a "good afternoon" at 5AM, which is obviously not correct :)
Can I get the time in the user's machine using PHP/JS, and if so, what function should I look at? Also, if JS is needed, how can I detect whether the user has a script blocker in place?
Sorry for the noobish questions, I am just starting to learn about web programming. Any help will be greatly appreciated. :)
Cheers! - jfabian
Upvotes: 0
Views: 235
Reputation: 678
My suggestion would be to have your PHP page return UTC time e.g. with gmdate() see get UTC time in PHP with UTC time you don't have to worry so much about things like daylight savings time, etc.
Then in your javascript you would determine the timezone offset of the user. You could use
new Date().getTimezoneOffset()
or for more advanced timezone stuff you may use a javascript library, see How to get user timezone using jquery? for some ideas.
Upvotes: 1
Reputation: 1575
PHP runs server side so it will only return the server time I believe.
Something like this in Javascript might work:
var currentTime = new Date()
var hours = currentTime.getHours()
var minutes = currentTime.getMinutes()
if (minutes < 10)
minutes = "0" + minutes
document.write("<b>" + hours + ":" + minutes + " " + "</b>")
Upvotes: 2
Reputation: 6389
You can get the user's timezone in javascript by using:
new Date().getTimezoneOffset() * -1
Upvotes: 1