Setting a greeting based on user's time (Good morning, good afternoon…)

后端 未结 6 2147
孤街浪徒
孤街浪徒 2021-02-02 11:13

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

6条回答
  •  南旧
    南旧 (楼主)
    2021-02-02 11:25

    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

提交回复
热议问题