44

I don't know JavaScript, but I am familiar with following directions. I know a little PHP.

I'm looking for a piece of JS that will output a particular string of text for my header, based on the user's current time.

For example:

12:00AM - 12:00PM - Good Morning!  
12:00PM - 6:00PM - Good Afternoon!  
6:00PM - 12:00AM - Good Evening!

17 Answers 17

109

Try following piece of Javascript code:

var today = new Date()
var curHr = today.getHours()

if (curHr < 12) {
  console.log('good morning')
} else if (curHr < 18) {
  console.log('good afternoon')
} else {
  console.log('good evening')
}
3
  • This works for me. Of course I had to change console.log to document.write to get it to output to the page. I chose this because it is simplest and works for my needs, although some others' answers below may be more correct. Dec 21, 2012 at 18:25
  • sir its not working for me properly because at evening in my clock time is 7O'clock but its return me 6 from currHr so tell me why get 6?
    – Kapil Soni
    Aug 22, 2019 at 13:34
  • This is good but Derek's answer's design is more elegant and dynamic instead of hard coding 3-4 if cases
    – Sisir
    Nov 7, 2021 at 19:07
17
var data = [
    [0, 4, "Good night"], 
    [5, 11, "Good morning"],          //Store messages in an array
    [12, 17, "Good afternoon"],
    [18, 24, "Good night"]
],
    hr = new Date().getHours();

for(var i = 0; i < data.length; i++){
    if(hr >= data[i][0] && hr <= data[i][1]){
        console.log(data[i][2]);
    }
}

Demo: http://jsfiddle.net/DerekL/we8Ty/

2
  • It's 12:21 by my computer clock, yet it said good morning. Is it possible that it only truncates the hours so, perhaps the array should say 0, 11? I have no idea, merely suggesting. Dec 21, 2012 at 18:22
  • @MikeMeldrem - I'm pretty sure it should be [0,11]... No idea why I put [0,12] before. Dec 22, 2012 at 5:00
10

This is just a small variation of the solution from Derek 朕會功夫 above.
I felt the array is cleaner than a bunch of if statements.
If you work the hours backwards, you don't need a start AND end hour.
Also, once you make a match, I added a break; to kick out early.

var data = [
    [22, 'Working late'],
    [18, 'Good evening'],
    [12, 'Good afternoon'],
    [5,  'Good morning'],
    [0,  'Whoa, early bird']
],
hr = new Date().getHours();
for (var i = 0; i < data.length; i++) {
    if (hr >= data[i][0]) {
        console.log(data[i][1])
        break;
    }
}
7

I know this is an old thread, i'm just sharing this 2 lines of code for anyone who needs simple solution :)

var hour = new Date().getHours();
console.log("Good " + (hour<12 && "Morning" || hour<18 && "Afternoon" || "Evening"))
3
const date = new Date();
const currentTime = date.getHours();

let greeting;

if (currentTime >= 0 && currentTime <= 12) {
  greeting = "Good Morning";
} else if (currentTime > 12 && currentTime <= 18) {
  greeting = "Good Afternoon";
} else {
  greeting = "Good Evening";
}

ReactDOM.render(
  <h1>{greeting}</h1>,
  document.getElementById("root")
);
1
  • Welcome to StackOverflow! Please explain your solution.
    – Jonathan
    Jul 29, 2021 at 17:47
3

This should help you:

const currentTime = new Date().getHours();
let greetingText = "";

if (currentTime < 12) {
  greetingText = "Good Morning"; 
} else if (currentTime < 18) {
  greetingText = "Good Afternoon"; 
} else {
  greetingText = "Good Evening"; 
}
2

How about:

var time = new Date().getHours();
   ,greeting = 'Good '+ (time < 12 ? 'Morning' : 
                         time < 18 ? 'Afternoon' : 'Evening');
//=> new Date('2012/11/06 13:10') => 'Good Afternoon'
//=> new Date('2012/11/06 10:33') => 'Good Morning'
//=> new Date('2012/11/06 19:23') => 'Good Evening'

Or augment Date

Date.prototype.greeting = function(){ 
   var time = this.getHours();
   return 'Good '+ (time<12 ? 'Morning' : time<18 ? 'Afternoon' : 'Evening');
};
new Date('2012/11/06 19:23').greeting() //=> 'Good Evening'

see jsfiddle

1

Try this js code, This should work..

var dt = new Date().getHours();
if (dt >= 0 && dt <= 11){
 console.log('GM')
}else if (dt >= 12 && dt <= 17){
 console.log('Good Afternoon!')
}else {
 console.log('GE')
}
1
  • What if you have a lot of time and text? The code will be so messy. Nov 6, 2012 at 5:47
0

I haven't tested but it should work:

function getText()
{
  var hour = new Date().getHours();
  var minute = new Date().getMinutes();
  if ( hour >= 0 && hour < 12 )
    return 'Good Morning!';
  else if ( hour == 12 && minute == 0 )
    return 'Good Morning!';
  else if ( hour == 12 && minute > 0 )
    return 'Good Afternoon!';
  else if ( hour == 6 && minute == 0 )
    return 'Good Afternoon!';
  else if ( hour == 6 && minute > 0 )
    return 'Good Evening!';
  else if ( hour > 12 && hour < 6 )
    return 'Good Afternoon!'; 
  else if ( hour > 6 && hour < 12 )
    return 'Good Evening';
}
0
<script type="text/javascript">

    var myDate = new Date();
    var name = window.prompt("Please enter your name: ");

    if (myDate.getHours() < 12) {
        document.write("Good Morning " +name);
    }
    else if(myDate.getHours() >=12 && myDate.getHours() <=17){
        document.write("Good Afternoon " +name);
    }
    else if (myDate.getHours() > 17 && myDate.getHours() <=24) {
        document.write("Good Evening " +name);
    }
    else
    {
        document.write("Good Night");
    }
</script>
0

With moment.js & ES6:

import moment from 'moment';

console.log(`${getGreetingTime(moment())} ${userFirstName}`);

getGreetingTime = (currentTime) => {
  if (!currentTime || !currentTime.isValid()) { return 'Hello'; }

  const splitAfternoon = 12; // 24hr time to split the afternoon
  const splitEvening = 17; // 24hr time to split the evening
  const currentHour = parseFloat(currentTime.format('HH'));

  if (currentHour >= splitAfternoon && currentHour <= splitEvening) {
    return 'Good afternoon';
  } else if (currentHour >= splitEvening) {
    return 'Good evening';
  }
  return 'Good morning';
}

Adapted from James1x0's gist.

1
  • It should be currentHour < splitEvening Aug 25, 2020 at 11:41
0
    var today = new Date();
    var curHr = today.getHours();

    if (curHr < 12) {
        console.log('good morning')
    } else if (curHr >= 12 && curHr < 16) {
        console.log('good afternoon')
    } else {
        console.log('good evening')
    }
0
var day=new Date();
var hr=day.getHours();
ReactDOM.render(
<div>
<h1>
{"Good"+ (hr< 12 ? "Morning": hr < 18 ? "Afternoon" :"Evening")}
</h1></div>,document.getElementById("root")); 
1
  • Welcome to Stack Overflow. Code-only answers are discouraged on Stack Overflow because they don't explain how it solves the problem. Please edit your answer to explain what this code does and how it improves on the other existing answers and upvoted answers that this question already has. Aug 18, 2020 at 18:43
0

This is what I used

import React from "react";
import ReactDOM from "react-dom"

const today = new Date().getHours();

let greeting;

if (today < 12) {
  greeting = "Good Morning"
} else if (today < 18) {
  greeting = "Good Afternoon"
} else {
  greeting = "Good Night"
}
1
  • Welcome to Stack Overflow. Code-only answers are discouraged on Stack Overflow because they don't explain how it solves the problem. Please edit your answer to explain what this code does and how it answers the problem described in the question, so that it is useful to other users with similar issues. Aug 27, 2020 at 2:06
0

Another way with ES6 and Moment.js

  import moment from 'moment';

  const getGreetingTime = () => {
    const splitMorning = 6;
    const splitAfternoon = 12;
    const splitEvening = 17;
    const splitNight = 20;
    const currentHour = parseFloat(moment().format('HH'));
    if (currentHour >= splitMorning && currentHour <= splitAfternoon) {
      return 'Good morning';
    } else if (currentHour >= splitAfternoon && currentHour <= splitEvening) {
      return 'Good afternoon';
    } else if (currentHour >= splitEvening && currentHour <= splitNight) {
      return 'Good evening';
    }
    return 'Good night';
  };

  const greeting = getGreetingTime();
0

Try this

if (hour >= 0 && hour < 3){
                return 'Good Late Night!';
            }
            else if (hour >= 3 && hour < 12){
                return 'Good Morning!';
            }
            else if (hour == 12 && minute == 0){
                return 'Good Morning!';
            }
            else if (hour == 12 && minute > 0){
                return 'Good Afternoon!';
            }
            else if (hour == 6 && minute == 0){
                return 'Good Afternoon!';
            }
            else if (hour == 6 && minute > 0){
                return 'Good Evening!';
            }
            else if (hour > 12 && hour <= 15){
                return 'Good Noon!';
            }
            else if (hour > 15 && hour <= 6){
                return 'Good Afternoon!';
            }
            else if (hour > 6 && hour < 12){
                return 'Good Evening';
            }
0

I have created a pure TypeScript function:

type SayHelloProps = {
  morning: string;
  afternoon: string;
  evening: string;
};

const sayHello = ({
  morning,
  afternoon,
  evening
}: SayHelloProps): string => {
  const currentTime = new Date();
  const currentHour = currentTime.getHours();

  switch (true) {
    case currentHour < 12:
      return morning;
    case currentHour > 12 && currentHour < 17:
      return afternoon;
    default:
      return evening;
  }
};

Readable, easy to use.

Not the answer you're looking for? Browse other questions tagged or ask your own question.