Paul
Paul

Reputation: 3368

Getting time and defining different variables with it

I created a function in which I am getting the time. Then setting variables to define morning, noon and evening. Finally calling the variables with the greeting variable.

I am unsure what I am doing wrong with the morningTime variable. The noonTime variable does work.

Does anyone see what I am doing wrong?

jsfiddle

 function timeNow() {
  
        var d = new Date(),
        h = (d.getHours() < 10 ? '0' + d.getHours() : '') + d.getHours(),
        m = (d.getMinutes() < 10 ? '0' + d.getMinutes() : '') + d.getMinutes();

        // To check for a time range (between 4:: and 11:30 here):
        var morningTime = (h >= 5 && h <= 12) ? true : false;
        var noonTime    = (h >= 12 && h <= 17) ? true : false;
        var nightTime   = (h >= 17 && h <= 5)  ? true : false;
        var greeting = "";

        if (morningTime) {
            greeting = "Good Morning";
        } else if (noonTime) {
            greeting = "Good Afternoon";
        } else if (nightTime) {
            greeting = "Good Evening";
        }

        return greeting;
    }
    document.getElementById('dashboard-hello').innerHTML = timeNow() + ', name!';
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="dashboard-hello" class="section-title"></div>

Upvotes: 0

Views: 31

Answers (1)

shuangwhywhy
shuangwhywhy

Reputation: 5625

h = (d.getHours() < 10 ? '0' + d.getHours() : '') + d.getHours(),
m = (d.getMinutes() < 10 ? '0' + d.getMinutes() : '') + d.getMinutes();

What I see from these two lines, you are contacting hours and minutes twice into a string.

If it's 09:09am, the code above gets you 099 as h, 099 as m.

If you want to keep 0 at left padding, you can do this:

h = ('0' + d.getHours()).slice(-2),
m = ('0' + d.getMinutes()).slice(-2),

Now get back to your problem, you don't actually need to do 0-padding at all, just try the following:

function timeNow() {

    var d = new Date(),
    h = d.getHours(),

    // To check for a time range (between 4:: and 11:30 here):
    var morningTime = h >= 5 && h <= 12;
    var noonTime    = h > 12 && h <= 17;
    var nightTime   = h > 17 && h < 5;
    var greeting = "";

    if (morningTime) {
        greeting = "Good Morning";
    } else if (noonTime) {
        greeting = "Good Afternoon";
    } else if (nightTime) {
        greeting = "Good Evening";
    }

    return greeting;
}
document.getElementById('dashboard-hello').innerHTML = timeNow() + ', name!';

Upvotes: 3

Related Questions