0

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

Paulo Freitas
  • 13,194
  • 14
  • 74
  • 96
jfabian
  • 19
  • 1
  • 5

3 Answers3

2

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>")
David Alsbright
  • 1,526
  • 1
  • 17
  • 31
  • 1
    +1. This is along the right approach. Just work in JavaScript, and it will always match the clock of the user. No need to involve time zones. If you want to make it even easier, use a library like [moment.js](http://momentjs.com). – Matt Johnson-Pint Nov 16 '13 at 02:49
1

You can get the user's timezone in javascript by using:

new Date().getTimezoneOffset() * -1
Paul Dessert
  • 6,363
  • 8
  • 47
  • 74
1

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.

Community
  • 1
  • 1
CodeMonkey
  • 629
  • 7
  • 16
  • Hint: `date_default_timezone_set('UTC');` will let you work with UTC time with any function that doesn't explicitly specify a timezone. :) – Paulo Freitas Nov 16 '13 at 01:07