views:

276

answers:

1

I'm sort of lost. Can anyone extrapolate on how to implement a basic "good evening" or "good morning" based on the user's time setting?

Perhaps PHP will fetch the server time, but I'm looking to greet the site visitor with a time-based appropriate greeting that considers their time of day.

E.G.: good morning, good night, good afternoon.

Thanks folks :)

+12  A: 

Base it on .getHours() of the date object. Using javascript's Date object will automatically use the user's local time, rather than the server-time:

var now = new Date();
alert( now.getHours() );

A couple conditional checks, and you're in business. For instance, the following is a very simple and easy-to-understand example:

var now = new Date();
var hrs = now.getHours();
var msg = "";

if (hrs >  0) msg = "Mornin' Sunshine!"; // REALLY early
if (hrs >  6) msg = "Good morning";      // After 6am
if (hrs > 12) msg = "Good afternoon";    // After 12pm
if (hrs > 17) msg = "Good evening";      // After 5pm
if (hrs > 22) msg = "Go to bed!";        // After 10pm

alert(msg);

It's currently 2:56am here, so I see "Mornin' Sunshine!" when I run this. You can test your own local time with this online demo: http://jsbin.com/aguyo3/edit

Jonathan Sampson
easy as cheesecakepie
Natrium
Remember to have a fallback in case the time could not be detected or when Javascript is disabled, e.g. preset `msg = 'Welcome'`.
Gordon
when javascript is disabled, you don't need `msg = 'Welcome'` cause there is no javascript
Natrium
@Gordon: Correct. This example is by no means suppose to be anything more than an example.
Jonathan Sampson
Also, I'd use a switch/case for this to be able to break after the first condition is met. No reason to check if hrs is e.g. greater 12 when it is not greater than 6. But good example nonetheless.
Gordon
@Natrium when the time could not be detected **or** when Javascript is disabled. In the latter case, you'd have to write Welcome somewhere else, presumabely as default innerHTML in a span reserved for greetings.
Gordon
ok, I agree :-)
Natrium