none
Message would not displayed based on time RRS feed

  • Question

  • Hello,

    I tried to display text on the screen base on the time.

    example : 

    if current time is 12:30 output should be "good after-non Jonh" but in my code something wrong i.e. after 12 pm output default expression . i am not able to find the problem please help me . 


    let today = new Date();
        let hours = today.getHours();
        let mins = today.getMinutes();
        let seconds = today.getSeconds();
        let totalSeconds = hours * 60 * 60 + mins * 60 + seconds;
        let msg = "";
        let flag;
        switch (flag) {
          case totalSeconds >= 0 && totalSeconds <= 43199:
            msg = "Good morning " + value;
            break;
          case totalSeconds >= 43200 && totalSeconds <= 53999:
            msg = "Good Afternon " + value;
            break;
          default:
            msg = "good evening " + value;
            break;
        }
        return msg;


    Wednesday, October 23, 2019 7:09 AM

All replies

  • This is not C#.

    I assume that

    let today = new Date();

    will initialize 'today' with a default Date value but not with the actual date/time. check, is theres something like 'Date.now()' This should do what you want.

    Wednesday, October 23, 2019 7:22 AM
  • What language is this - JavaScript, TypeScript, F#, etc?

    Michael Taylor http://www.michaeltaylorp3.net

    Wednesday, October 23, 2019 1:57 PM
  • You do not need to use minutes and seconds here.  Your code is equivalent to:

        switch(flag) {
            case hours >= 0 && hours < 12:
        ...
            case hours >= 12 && hours < 15:

    The root of your problem is that you are using the switch statement incorrectly.  There are languages where the "case" statement can have arbitrary conditional expressions like that, but Javascript is not one of them.  Your code is switching based on an uninitialized variable.  You need to use an if/else chain:

        let today = new Date();
        let hours = today.getHours();
        let msg = "";
        if( hours >= 0 && hours < 12 )
            msg = "Good morning " + value;
        else if( hours < 15 )
            msg = "Good Afternon " + value;
        else
            msg = "good evening " + value;
        return msg;
    Also, next time, do not post Javascript questions in a C# forum.


    Tim Roberts | Driver MVP Emeritus | Providenza &amp; Boekelheide, Inc.

    Wednesday, October 23, 2019 10:48 PM