JavaScript time greeting? - javascript

How do you make something with JavaScript that when your time is below 12 o'clock, it says "good morning!" and when it is after 12 o'clock, it says "good afternoon!"?

Here it is!
var d = new Date();
var time = d.getHours();
if (time < 12) {
document.write("<b>Good morning!</b>");
}
if (time > 12) {
document.write("<b>Good afternoon!</b>");
}
if (time == 12) {
document.write("<b>Go eat lunch!</b>");
}

const date = new Date;
let hours = date.getHours();
let status = (hours < 12)? "Morning" :
((hours <= 18 && hours >= 12 ) ? "Afternoon" : "Night");
console.log(status);

The following should work:
var hours = new Date().hours;
if(hours > 12){
alert("Good Afternoon!");
}
else{
alert("Good Morning!");
}
Just for fun, here's a one liner:
(new Date().hours > 12) ? alert("Good Afternoon!") : alert("Good Morning!");
Working Demo

<SCRIPT LANGUAGE="JavaScript">
currentTime=new Date();
//getHour() function will retrieve the hour from current time
if(currentTime.getHours()<12)
document.write("<b>Good Morning!! </b>");
else if(currentTime.getHours()<17)
document.write("<b>Good Afternoon!! </b>");
else
document.write("<b>Good Evening!! </b>");
</SCRIPT>

//if hour is between 6am-12pm ,print good morning
//if hour is between 12pm-6pm ,print good afternoon
//else good evening
let hour = 5;
if(hour>=6 && hour<12) {
console.log('Good Morning')
}
else if(hour>+12 && hour<18) {
console.log('Good Afternoon')
}
else {
console.log('Good Evening')
}

<script type="text/javascript">
document.write("<h2>");
var day = new Date();
var hr = day.getHours();
if (hr >= 4 && hr < 12) {
document.write("Goedenmorgen");
} else if (hr == 12) {
document.write("Goedemiddag");
} else if (hr >= 12 && hr <= 16) {
document.write("Goedemiddag");
} else if (hr >= 16 && hr <= 23) {
document.write("Goedenavond");
} else {
document.write("Goedennacht");
}
document.write("</h2>");
</script>

Related

Javascript IF/ELSE - Shorten function

I am playing around with the JavaScript IF/ELSE to understand better how it works. As an exercise I took the following working hours of a shop:
6AM to 6PM = Open
6PM to 6AM = Closed
then I created a function that returns the word 'Open' or 'Closed' based on the 2 values "time" and "period".
function shopHours(time,period) {
if (time === 6 && period === 'AM') {
return 'Open';
} else if (time === 6 && period === 'AM') {
return 'Open';
} else if (time === 7 && period === 'AM') {
return 'Open';
} else if (time === 8 && period === 'AM') {
return 'Open';
} else if (time === 9 && period === 'AM') {
return 'Open';
} else if (time === 10 && period === 'AM') {
return 'Open';
} else if (time === 11 && period === 'AM') {
return 'Open';
} else if (time === 12 && period === 'PM') {
return 'Open';
} else if (time === 1 && period === 'PM') {
return 'Open';
} else if (time === 2 && period === 'PM') {
return 'Open';
} else if (time === 3 && period === 'PM') {
return 'Open';
} else if (time === 4 && period === 'PM') {
return 'Open';
} else if (time === 5 && period === 'PM') {
return 'Open';
} else {
return 'Closed';}
}
Everything works fine. However, I would like to be able to shorten the code as it looks too confusing.
I then tried the following:
function shopHours(time,period) {
if(time <= 6 && period === 'AM') {
return 'Closed';
} else if (time >= 6 && period === 'PM') {
return 'Closed';
} else if (time === 12 && period === 'PM') {
return 'Open';
} else {
return 'Open';}
}
The second code works fine too and is much shorter however there is a problem that I am not sure how to solve. When the time and period are set to 12 and PM, the result should be 'closed' but I am not sure how to implement this.
I have tried to add the following code but it seems that would not solve this problem.
else if (time === 12 && period === 'AM') {
return 'Closed';
}
I will be very grateful to anyone that will spend a bit of his time to take a look at this question.
Thank you!
You can break it down into two initial scenarios, either AM or PM. Then check the hour to see if it should be open or closed.
if (period == "AM") {
if (time < 6 || time == 12)
return "Closed";
return "Open";
}
else {
if (time >= 6 && time != 12)
return "Closed";
return "Open";
}
It's easier to work with 24-hour format, in my opinion.
One has to take 12PM = 12:00 and 12AM = 00:00 into account however.
After conversion the comparision is fairly easy.
function shopHours(time, period) {
let hour = time;
if (period === 'PM' && hour < 12) hour = hour + 12;
if (period === 'AM' && hour === 12) hour = hour - 12;
if (hour >= 6 && hour < 18) {
return 'Open';
}
return 'Closed';
}
console.log('12 AM is ' + shopHours(12, 'AM') + '. Expected it to be: Closed');
console.log('3 AM is ' + shopHours(3, 'AM') + '. Expected it to be: Closed');
console.log('6 AM is ' + shopHours(6, 'AM') + '. Expected it to be: Open');
console.log('9 AM is ' + shopHours(9, 'AM') + '. Expected it to be: Open');
console.log('12 PM is ' + shopHours(12, 'PM') + '. Expected it to be: Open');
console.log('3 PM is ' + shopHours(3, 'PM') + '. Expected it to be: Open');
console.log('6 PM is ' + shopHours(6, 'PM') + '. Expected it to be: Closed');
console.log('9 PM is ' + shopHours(9, 'PM') + '. Expected it to be: Closed');
My version.if goal is to just shorten the code, then those am() and pm() functions can be omitted and the code inside can be added where am calling them. That would be 3 lines of code.
function shopHours(time, period){
var result;
function am () {
Number(time) < 12 && Number(time) >= 6 ? result = "open" : result = "closed";
}
function pm() {
Number(time) <= 5 || Number(time) === 12 ? result = "open" : result = "closed";
}
period === 'AM' ? am() : pm();
return result;
}
console.log("12 AM is: ", shopHours(12, 'AM'), '; expected: closed');
console.log("3 AM is: ", shopHours(3, 'AM'), '; expected: closed');
console.log("6 AM is: ", shopHours(6, 'AM'), '; expected: open');
console.log("9 AM is: ", shopHours(9, 'AM'), '; expected: open');
console.log("12 PM is: ", shopHours(12, 'PM'), '; expected: open');
console.log("3 PM is: ", shopHours(3, 'PM'), '; expected: open');
console.log("6 PM is: ", shopHours(6, 'PM'), '; expected: closed');
console.log("9 PM is: ", shopHours(9, 'PM'), '; expected: closed');
This can be easily handled using date instead. Instead of using if else, You can define the openHours and closeHours. And pass the current time. You can easily compare then.
Sample:
function shopHours(time, period) {
let openHour = new Date();
let closeHour = new Date();
openHour.setHours(6);
closeHour.setHours(12 + 6);
let curreTime = new Date();
curreTime.setHours(period === "PM" ? 12 + time : time);
if (curreTime > openHour && curreTime < closeHour) return "Open";
return "Close";
}
console.log(shopHours(11, "PM"));
console.log(shopHours(12, "AM"));
console.log(shopHours(11, "AM"));
console.log(shopHours(7, "AM"));
console.log(shopHours(5, "AM"));
You can also just pass the currentTime and validate.
function shopHours(curreTime) {
let openHour = new Date();
let closeHour = new Date();
openHour.setHours(6);
closeHour.setHours(12 + 6);
if (curreTime > openHour && curreTime < closeHour) return "Open";
return "Close";
}
console.log(shopHours(new Date()));
My suggestion:
function shopHours(time, period) {
var status = "Open";
if ((period == "AM" && (time < 6 || time == 12)) || (time >= 6 && time != 12)) status = "Closed";
return status;
}
console.log(shopHours(5, "AM"));
console.log(shopHours(5, "PM"));

"sbox_fatal_memory_exceeded" - Javascript Countdown Function

I am fairly new to JS and don't know much.
So I tried to make a simple countdown for work, so I can see how long I have to work. It takes the actual time and just subtracts it from the time till I have to work. So very simple.
When I keep the website open for more than 20 mins, it crashes and Chrome/Edge/Firefox displays the ERROR message: ''SBOX_FATAL_MEMORY_EXCEEDED".
I think, due to the fact, that I am recalling the function with an unaccasary amount of ifs, the Browser gets drained quickly out of memory. That's at least what I think. But I can not get it to work. Nevermind how I rewrite my function, it still crashes.
Would be happy if someone can help me, or link me a similar StackOverflow question, 'cause the few results for this error in combination with js didn't help me.
Here is the JS code:
//CSS ELEMETNS
var helloText = document.getElementById("welcomeText");
var textFiller = document.getElementById("fillerText");
var countdown = document.getElementById("countdown");
var motivationText = document.getElementById("motivationText");
var btn = document.getElementById("button");
//JS VARs
let date, hrs, mins, secs;
let date = new Date();
//main function to check which day it is, and which function to call
function clock() {
let day = date.getDay());
if (day == 0 || day == 6) {
weekend();
} else if (day == 5) {
friday();
} else {
otherDay();
}
}
//Text to display if it is sun or sat
function weekend() {
helloText.innerHTML = "Juhu!";
countdown.innerHTML = "Es ist Wochenende!";
textFiller.innerHTML = "";
btn.style.display = "none";
}
//Function to execute when it is friday
function friday() {
hrs = date.getHours();
mins = date.getMinutes();
secs = date.getSeconds();
hrs = hrs < 10 ? `0${hrs}` : hrs;
mins = mins < 10 ? `0${mins}` : mins;
secs = secs < 10 ? `0${secs}` : secs;
if (hrs >= 14 || hrs < 7) {
if ((((helloText.innerHTML != "Yeah!" &&
countdown.innerHTML != "You can go home!") &&
textFiller.innerHTML != "") &&
btn.style.display != "none")) {
helloText.innerHTML = "Yeah!";
countdown.innerHTML = "You can go home!";
textFiller.innerHTML = "";
btn.style.display = "none";
}
} else {
if (hrs < 10) {
if (helloText.innerHTML != "Good Morning!" &&
motivationText.innerHTML !=
"Man, it is still early in the morning...") {
helloText.innerHTML = "Good Morning!";
motivationText.innerHTML =
"Man, it is still early in the morning...";
}
}
if (hrs == 10 || hrs > 10) {
if (helloText.innerHTML != "Hello!" &&
motivationText.innerHTML !=
"Stay concentrated! The morning is already over!") {
helloText.innerHTML = "Hello!";
motivationText.innerHTML =
"Stay concentrated! The morning is already over!";
}
}
if (hrs == 12 || hrs > 12) {
if (motivationText.innerHTML != "You almost got it!") {
motivationText.innerHTML = "You almost got it!";
}
}
if (hrs == 13 || hrs > 13) {
if (motivationText.innerHTML !=
"Finally! The last hour!") {
motivationText.innerHTML =
"Finally! The last hour!";
}
}
hrs = 13 - hrs;
mins = 59 - mins;
secs = 60 - secs;
if (hrs < 10) {
hrs = "0" + hrs;
}
if (mins < 10) {
mins = "0" + mins;
}
if (secs < 10) {
secs = "0" + secs;
}
let time = `${hrs}:${mins}:${secs}`;
setInterval(clock, 1000);
countdown.innerText = time;
}
}
//otherday() is the same as friday(), just with different hours
Your script was not working at all
This works. Take it from there
I moved the setInterval outside all functions and new Date inside clock
//CSS ELEMETNS
var helloText = document.getElementById("welcomeText");
var textFiller = document.getElementById("fillerText");
var countdown = document.getElementById("countdown");
var motivationText = document.getElementById("motivationText");
var btn = document.getElementById("button");
//JS VARs
let date, hrs, mins, secs;
//main function to check which day it is, and which function to call
function clock() {
date = new Date();
let day = date.getDay();
if (day == 0 || day == 6) {
weekend();
} else if (day == 5) {
friday();
} else {
// otherDay();
friday()
}
//Text to display if it is sun or sat
function weekend() {
helloText.innerHTML = "Juhu!";
countdown.innerHTML = "Es ist Wochenende!";
textFiller.innerHTML = "";
btn.style.display = "none";
}
//Function to execute when it is friday
function friday() {
hrs = date.getHours();
mins = date.getMinutes();
secs = date.getSeconds();
hrs = hrs < 10 ? `0${hrs}` : hrs;
mins = mins < 10 ? `0${mins}` : mins;
secs = secs < 10 ? `0${secs}` : secs;
let time = `${hrs}:${mins}:${secs}`;
countdown.innerText = time;
if (hrs >= 14 || hrs < 7) {
if ((((helloText.innerHTML != "Yeah!" &&
countdown.innerHTML != "You can go home!") &&
textFiller.innerHTML != "") &&
btn.style.display != "none")) {
helloText.innerHTML = "Yeah!";
countdown.innerHTML = "You can go home!";
textFiller.innerHTML = "";
btn.style.display = "none";
}
} else {
if (hrs < 10) {
if (helloText.innerHTML != "Good Morning!" &&
motivationText.innerHTML !=
"Man, it is still early in the morning...") {
helloText.innerHTML = "Good Morning!";
motivationText.innerHTML =
"Man, it is still early in the morning...";
}
}
if (hrs == 10 || hrs > 10) {
if (helloText.innerHTML != "Hello!" &&
motivationText.innerHTML !=
"Stay concentrated! The morning is already over!") {
helloText.innerHTML = "Hello!";
motivationText.innerHTML =
"Stay concentrated! The morning is already over!";
}
}
if (hrs == 12 || hrs > 12) {
if (motivationText.innerHTML != "You almost got it!") {
motivationText.innerHTML = "You almost got it!";
}
}
if (hrs == 13 || hrs > 13) {
if (motivationText.innerHTML !=
"Finally! The last hour!") {
motivationText.innerHTML =
"Finally! The last hour!";
}
}
hrs = 13 - hrs;
mins = 59 - mins;
secs = 60 - secs;
if (hrs < 10) {
hrs = "0" + hrs;
}
if (mins < 10) {
mins = "0" + mins;
}
if (secs < 10) {
secs = "0" + secs;
}
}
}
}
setInterval(clock, 1000);
//otherday() is the same as friday(), just with different hours
<span id="welcomeText"></span>
<span id="fillerText"></span>
<span id="motivationText"></span>
<span id="countdown"></span>
<button type="button" id="button">Button</button>

displaying person before greeting

Hi I need those two to show in the same line(Now they show one after another). I tried many things but nothing works.
document.write();
var day = new Date();
var hr = day.getHours();
if ((hr == 1) || (hr == 2) || (hr == 3) || (hr == 4) || (hr == 5) || (hr ==
6) || (hr == 7) || (hr == 8) || (hr == 9) || (hr == 10) || (hr == 11) ||
(hr == 12)) {
document.write("Good Morning!");
}
if ((hr == 13) || (hr == 14) || (hr == 15) || (hr == 16) || (hr == 17)) {
document.write("Good Afternoon!");
}
if ((hr == 18) || (hr == 19) || (hr == 20) || (hr == 21) || (hr == 22) ||
(hr == 23) || (hr == 24)) {
document.write("Good Evening!");
}
document.write();
/*--------------------------------------------------------------------------
---------------------------*/
function myFunction() {
var person = prompt("Please enter your name", "Harry Potter");
if (person != null) {
document.getElementById("demo").innerHTML =
person;
}
}
Is this what you are looking for:
<html>
<body onload="myFunction()">
<div id="demo"></div>
<script>
function myFunction() {
var day = new Date();
var hr = day.getHours();
var greeting;
var person = prompt("Please enter your name", "Harry Potter");
if (person != null) {
if ( hr <= 12 ) {
greeting = "Good morning " + person;
} else if ( hr <= 18 ) {
greeting = "Good afternoon " + person;
} else {
greeting = "Good evening " + person;
}
document.getElementById("demo").innerHTML = greeting;
}
}
</script>
</body>
</html>
I hope this'll Help you. i also done code optimization for if
Conditions.
You have to invoke myfunction method
<body>
<span id="demo"></span>
<script>
(function () {
var person = prompt("Please enter your name", "Harry Potter");
if (person != null) {
document.write();
var day = new Date();
var hr = day.getHours();
if ((hr >= 1) && (hr <= 12)) {
person = person + " Good Morning!";
}
else if ((hr >= 13) && (hr <= 17)) {
person = person + " Good Afternoon!";
}
else if ((hr >= 18) && (hr <= 24)) {
person = person + "Good Evening!" ;
}
document.getElementById("demo").innerHTML = person;
}
})()
</script>
</body>
document.write() does not add a new line to document but rather changes your document element to the content, where as document.getElementById() refers to specific element in the DOM. Anyway here is my
javascript:
function greeting() {
var person = prompt("Please enter your name", "Harry Potter");
if (person != null) {
// Set hr to current hour
var hr = new Date().getHours();
// Tests current hour
if (hr > 0 && hr < 13) {
document.write("Good Morning! " + person);
} else if (hr > 12 && hr < 18) {
document.write("Good Afternoon! " + person);
} else if (hr > 17 && hr < 25) {
document.write("Good Evening! " + person);
}
}
}

A function inside of the h1 tag?

I want to insert my function inside of the h1 tag so it will address the user a greeting depending on the time of day. This is my time function but how do I implement it into h1?
var today = new Date();
var curHr = today.getHours();
function greeting() {
if ( curHr < 12) {
document.write('Good Morning');
} else if ( curHr < 18) {
document.write('Good Afternoon');
} else if ( curHr < 20) {
document.write('Good Evening')
} else {
document.write('Good Night');
}
}
You give your H1 an ID
<h1 id="goeshere">Message</h1>
You then replace document.write with something like
document.getElementById('goeshere').textContent = 'Good Morning'.
and do that for all the conditions.
You do not put the javascript inside the H1, and you do not use document.write, ever !
var today = new Date();
var curHr = today.getHours();
function greeting() {
if ( curHr < 12) {
document.getElementById('goeshere').textContent = 'Good Morning';
} else if ( curHr < 18) {
document.getElementById('goeshere').textContent = 'Good Afternoon';
} else if ( curHr < 20) {
document.getElementById('goeshere').textContent = 'Good Evening';
} else {
document.getElementById('goeshere').textContent = 'Good Night';
}
}
greeting()
<h1 id="goeshere">Message</h1>
I think you're trying to write a function that is suppsoed to update the header tag.
You should fetch the date within the function (no need in globals). The function should return desired value (instead of document.write). And you should use the function as appropriate, for example:
function greeting() {
var today = new Date();
var curHr = today.getHours();
if ( curHr < 12) {
return 'Good Morning';
} else if ( curHr < 18) {
return 'Good Afternoon';
} else if ( curHr < 20) {
return 'Good Evening';
} else {
return 'Good Night';
}
}
var h1 = document.getElementById('my-header');
// Check if such header actually exists
if (h1) {
h1.innerHTML = greeting();
}
It is assumed that the code is executed somewhere after the h1 tag (the tag should be available when we access it), for example:
<h1 id="my-header">Default header</h1>
<!-- ... -->
<script>/* here */</script>
You put a script that calls it there.
<h1><script>greeting()</script></h1>
you could try in such a way also
var today = new Date();
var curHr = today.getHours();
function greeting() {
if ( curHr < 12) {
return 'Good Morning';
} else if ( curHr < 18) {
return 'Good Afternoon';
} else if ( curHr < 20) {
return 'Good Evening';
} else {
return 'Good Night';
}
}
var xyz= greeting()
//alert(xyz)
document.getElementById('yourElementId').textContent =xyz
have a look at here is working example.

`if (Date >= Date1 && <= Date2 ){do this}` dosnĀ“t work

The code changes the new Date() to DayHourMinute
e.g. monday9AM45minutes to 010945
What I use is 010945 and my code specifies
if the var is between >=010921 && <=011010
change the background to green else nothing
But nothing happens and if I use alert(Time) it gives the message 010945.
How can if fix this?
Code:
function one() {
now = new Date();
hour = "" + now.getHours();
if (hour.length == 1) {
hour = "0" + hour;
}
minute = "" + now.getMinutes();
if (minute.length == 1) {
minute = "0" + minute;
}
day = "" + now.getDay();
if (day.length == 1) {
day = "0" + day;
}
var Time = day + '' + hour + '' + minute;
if (Time >= 010835 && Time <= 010920) {
document.getElementById('Man1').style.background = 'green';
} else {
document.getElementById('Man1').style.background = '';
}
if (Time >= 010921 && Time <= 011010) {
document.getElementById('Man2').style.background = 'green';
} else {
document.getElementById('Man2').style.background = '';
}
if (Time >= 011011 && Time <= 011105) {
document.getElementById('Man3').style.background = 'green';
} else {
document.getElementById('Man3').style.background = '';
}
if (Time >= 011106 && Time <= 011155) {
document.getElementById('Man4').style.background = 'green';
} else {
document.getElementById('Man4').style.background = '';
}
if (Time >= 011156 && Time <= 011239) {
document.getElementById('Man5').style.background = 'green';
} else {
document.getElementById('Man5').style.background = '';
}
if (Time >= 011240 && Time <= 011325) {
document.getElementById('Man6').style.background = 'green';
} else {
document.getElementById('Man6').style.background = '';
}
if (Time >= 011326 && Time <= 011415) {
document.getElementById('Man7').style.background = 'green';
} else {
document.getElementById('Man7').style.background = '';
}
if (Time >= 011416 && Time <= 011505) {
document.getElementById('Man8').style.background = 'green';
} else {
document.getElementById('Man8').style.background = '';
}
if (Time >= 011506 && Time <= 011555) {
document.getElementById('Man9').style.background = 'green';
} else {
document.getElementById('Man9').style.background = '';
}
}
setInterval(one, 1000);
Fiddle
Time is a string, and you are comparing to an int. Put the values in quotes:
if ( Time>='020000' && Time<='030000' ){

Categories