Display greeting (morning/afternoon/evening) using both hours and minutes - javascript

I am trying to write an HTML document that displays a greeting to visitors, like "Good Morning/Afternoon/Evening!"
But I don't know how to use both hours and minutes together:
<html>
<head>
<title>ITP1</title>
</head>
<body>
<label id="TIME"></label>
</body>
<script>
var myDate = new Date();
var hrs = myDate.getHours();
var mins = date.getMinutes();
var greet;
if (hrs >= 12 && hrs <= 11.59)
greet = 'Good Morning';
else if (hrs >= 12 && hrs <= 17)
greet = 'Good Afternoon';
else if (hrs >= 17 && hrs <= 24)
greet = 'Good Evening';
document.getElementById('TIME').innerHTML =
'<b>' + greet;
</script>
</html>
I want to set ranges for morning/evening/afternoon using both hours and minutes with these ranges:
Evening: 0:00 to 5:29
Morning: 5:30 to 11:59
Afternoon: 12:00 to 17:59
Evening: 18:00 to 24:00

First, change date.getMinutes() to myDate.getMinutes().
Then, you can compare them like this:
if (hrs >= 5 && ((hrs == 5 && mins >= 30) || (hrs > 5 && hrs < 12)))
greet = 'Good Morning';
else if (hrs >= 12 && hrs < 18)
greet = 'Good Afternoon';
else if ((hrs >= 18 && hrs < 24) || hrs > 0)
greet = 'Good Evening';
else
greet = 'Error';
Note that I added an else at the end for weird cases.
The snippet below shows this in action. Don't worry about the other code; it's just there to make the tests output readable.
function doATest(timeIn) {
var myDate = new Date(timeIn ? "0 " + timeIn : null);
var hrs = myDate.getHours();
var mins = myDate.getMinutes(); // changed date to myDate
var greet;
// morning | 5:30-11:59
// afternoon | 12:00-17:59
// evening | 18:00-05:29
if (hrs >= 5 && ((hrs == 5 && mins >= 30) || (hrs > 5 && hrs < 12)))
greet = 'Good Morning';
else if (hrs >= 12 && hrs < 18)
greet = 'Good Afternoon';
else if ((hrs >= 18 && hrs < 24) || hrs > 0)
greet = 'Good Evening';
else
greet = 'Error';
document.getElementById('timeTable').innerHTML +=
'<tr>' +
'<td>' + (timeIn ? timeIn : "Right Now") + '</td>' +
'<td>' + greet + '</td>' +
'</tr>';
}
doATest("1:00");
doATest("1:37");
doATest("5:00");
doATest("5:15");
doATest("5:29");
doATest("5:29:59");
doATest("5:30");
doATest("5:45");
doATest("6:00");
doATest("6:15");
doATest("6:30");
doATest("6:45");
doATest("6:45");
doATest("7:00");
doATest("waffles"); // not valid
doATest("9:45");
doATest("11:00");
doATest("11:30");
doATest("11:45");
doATest("11:59");
doATest("11:59:59");
doATest("12:00");
doATest("12:34");
doATest("12:48");
doATest("13:00");
doATest("13:57");
doATest("15:00");
doATest("17:00");
doATest("17:20");
doATest("17:40");
doATest("17:59");
doATest("17:59:59.999");
doATest("18:00");
doATest("17:76"); // not valid
doATest("18:36");
doATest("18:63"); // not valid
doATest("19:00");
doATest("20:00");
doATest("23:00");
doATest("24:00"); // really 0:00 the next day
doATest("27:00"); // not valid
<html>
<head>
<title>ITP1</title>
</head>
<body>
<table>
<thead>
<tr>
<th>Time</th>
<th>Greeting</th>
</tr>
</thead>
<tbody id="timeTable"></tbody>
</table>
</body>
</html>

Related

Check if time is within time bounds with minutes

looking for help in changing the working hours from 8 to 5 to 8:30 to 5:30. would appreciate some help with amending the existing JavaScript function:
<html>
<head>
<script>
onload = function ( )
{
var now = new Date();
var weekday = now. getDay();
var hours = now.getHours();
if ((hours >= 8) && (hours <= 5)) && ((weekday >=1) && (weekday <= 5))
{
document.getElementById("status").src="open.png";
}
else
{
document.getElementById("status").src="closed.png";
}
}
</script>
</head>
<body>
<img id="status" src="">
</body>
</html>
Since .getHours() returns an integer, check the hour and the minutes accordingly using .getMinutes().
It's a bit messy, but it's easy to understand. I've broken it down below the snippet.
const cur = new Date();
const minutes = cur.getMinutes();
const h = cur.getHours();
const d = cur.getDay();
let closed = true;
if ((d >= 1) && (d <= 5)) {
if (h > 8 && h < 17) {
if (h == 8 && minutes < 30 || h == 17 && minutes > 30) {
closed = true;
} else {
closed = false;
}
} else {
closed = true;
}
} else {
closed = true;
}
console.log("Closed? : " + closed);
(d >= 1) && (d <= 5) - this checks whether the weekday is within the bounds of Monday (1) and Friday (5)
(h > 8 && h < 17) - is the current hour within the bounds 8 AM and 5 PM (8 and 17 respectively)?
h == 8 && minutes < 30 || h == 17 && minutes > 30 - if the current hour is 8, check if the minutes is smaller than 30. We need to ensure that the minutes is 30 or greater (8:30+). If the current hour is 5, check if the minutes is greater than 30. We need to ensure that the minutes is 30 or less (5:30-). If any of these are satified, we know it is closed.
Here's a comprehensive snippet with logs:
const cur = new Date();
const minutes = cur.getMinutes();
const h = cur.getHours();
const d = cur.getDay();
let closed = true;
if ((d >= 1) && (d <= 5)) {
console.log("Weekday is within Monday and Friday? check");
if (h > 8 && h < 17) {
console.log("Hour is between 8 AM and 5PM? check");
if (h == 8 && minutes < 30 || h == 17 && minutes > 30) {
console.log("Minutes is more then 30 if hour is 8 or minutes is less than 30 if hour is 15? fail");
closed = true;
} else {
console.log("Minutes is more then 30 if hour is 8 or minutes is less than 30 if hour is 15? check");
closed = false;
}
} else {
console.log("Hour is between 8 AM and 5PM? fail");
closed = true;
}
} else {
console.log("Weekday is within Monday and Friday? fail");
closed = true;
}
console.log("Closed? : " + closed);
Here's what it should look like in your particular example:
<html>
<head>
<script>
onload = function() {
const cur = new Date();
const minutes = cur.getMinutes();
const h = cur.getHours();
const d = cur.getDay();
let closed = true;
if ((d >= 1) && (d <= 5)) {
if (h > 8 && h < 17) {
if (h == 8 && minutes < 30 || h == 17 && minutes > 30) {
closed = true;
} else {
closed = false;
}
} else {
closed = true;
}
} else {
closed = true;
}
if (closed) {
document.getElementById("status").src = "closed.png";
} else {
document.getElementById("status").src = "open.png";
}
}
</script>
</head>
<body>
<img id="status" src="">
</body>
</html>
first of all, you mistakenly added extra bracket in your if expression:
if ((hours >= 8) && (hours <= 5)) && ((weekday >=1) && (weekday <= 5))
I ecountered this seemingly easy to solve in past, until you need to compare the minutes inbetween, you will run to unecessary complex logic.
the cleanest way to solve this is convert into "seconds from midnight" which makes easier for comparison between two time. (this technique similar to UNIX TIME technique use by lots of date system nowdays, you can google it)
in smaller project its ok to do following:
var now = new Date();
var weekday = now.getDay();
function getSecond(hours, minutes){
return ( (hours * 60 * 60) + (minutes * 60) ); //this will return the total seconds past midnight
}
//converting to seconds to certain point of time is used by "timestamp" technique, you can google bout it
let openSeconds = getSecond(8,30);
let closeSeconds = getSecond(17,30);
let nowSeconds = getSecond( now.getHours(), now.getMinutes());
console.log(openSeconds + ' ' + closeSeconds + ' ' + nowSeconds);
if( (weekday >= 1) && (weekday <= 5) ){ //Weekday validation
if(openSeconds < nowSeconds && nowSeconds <= closeSeconds){ //inclusive, ( < or <= ) you decide
document.getElementById("status").src = "open.png";
}else{
document.getElementById("status").src = "closed.png";
}
}
in bigger project, i always always recommend to use dayjs or moment js to deal with timezones like explained in video:
https://www.youtube.com/watch?v=-5wpm-gesOY
Adapting the code you posted:
window.onload = function () {
var now = new Date();
var weekday = now.getDay();
var hours = now.getHours();
var minutes = now.getMinutes();
var status = document.getElementById('status');
// if Monday - Friday
if (weekday >= 1 && weekday <= 5) {
// if before 8am OR after 5pm
if (hours < 8 || hours > 17) {
status.src = 'closed.png';
}
// if less than 30 minutes past 8am, OR
// if 30+ minutes past 5pm
else if (minutes < 30 && hours === 8 || minutes >= 30 && hours === 17) {
status.src = 'closed.png';
}
// if 30 or more minutes past any hour between 8am and 4pm,
// or up to 29 minutes past 5pm, you're open!
else {
status.src = 'open.png';
}
}
};

Javascript time between 08:30 - 20:00

I am trying to make a message show between certain time ranges in a day but i cant make it work it either shows the first IF or doesnt show anything at all with an error i cant seem to figure out. what am i doing wrong?
var today = new Date();
var hour = today.getHours();
var minute = today.getMinutes();
if(today.getDay() == 4){
if(hour > 8 && minute > 30 || hour < 20){
document.getElementById('test').innerHTML = ('come today till 20:00');
} else if (hour > 20 && hour < 0){
document.getElementById('test').innerHTML = ('Come tomorrow till 20:00');
} else (hour > 0 && hour < 8).document.getElementById('test').innerHTML = ('Come today from 08:00 till 20:00');
}
figured it out thanks for the help guys :)
this is how it works now.
if(today.getDay() == 4){
if((hour === 8 && minute > 30 || hour > 8) && hour < 20){
document.getElementById('test').innerHTML = ('Kom vandaag langs in onze showtuin tot 20:00 uur donderdag');
} else if (hour >= 20 && hour < 24){
document.getElementById('test').innerHTML = ('Kom morgen langs in onze showtuin tot 20:00 uur');
} else{
document.getElementById('test').innerHTML = ('Kom vandaag langs in onze showtuin van 08:00 tot 20:00 donderdag');
}
}
You could simplify the conditions a bit, with checking from small values to greater values, like
if (today.getDay() == 4) {
if (hour < 8) {
document.getElementById('test').innerHTML = 'Come today from 08:00 till 20:00';
} else if (hour < 20) {
document.getElementById('test').innerHTML = 'Come today till 20:00';
} else if (hour < 24) {
document.getElementById('test').innerHTML = 'Come tomorrow till 20:00';
}
}
Working with absolute minute may become simplier:
var today = new Date();
var crtminut = ((today/60000).toFixed(0)-today.getTimezoneOffset())%1440;
var minmin = 8*60+30;
var minmax = 20*60;
if (today.getDay() == 4) {
if ((minmin <= crtminut) && (crtminut < minmax)) {
... inner period
} else {
... outer period
}
}
Each if can use the previous condition to its advantage which means if you correctly sort the conditions you can make it really simple:
if (hour >= 20) {
//20:00 - 23:59
}
else if (hour > 8) {
//9:00 - 19:59
}
else if (hour == 8 && minute >= 30) {
//8:30 - 8:59
}
else {
//0:00 - 8:29
}

time of day based div refresh

Hey, how do you refresh a div on a certain hour?
So the timed based greeting ticks over automatically.
the code I have at the moment is this:
<div id = "greet" ><script>
var Digital=new Date()
var hours=Digital.getHours()
if (hours < 12)
document.write('Good morning.')
else if (hours >= 12 && hours < 18)
// (code in here?) refresh the div at 12:00 pm
document.write('Good afternoon.')
else if (hours >= 18 && hours <= 24)
// (code in here?) refresh div at 6:00 pm
document.write('Good evening.')
</script></div>
any tips would be great.
cheers.
are you need like this
var datas="";
var Digital=new Date()
var hours=Digital.getHours()
if (hours < 12){
datas = 12 ? "is a below 12am" : "";
document.write('Good morning.')
}
else if (hours >= 12 && hours < 18) {
datas = 12 ? "is a 12am" : "";
document.write('Good afternoon.')}
else if (hours >= 18 && hours <= 24){
datas = 18 ? "is a 6pm" : "";
document.write('Good evening.')
}
document.getElementById('greet').innerHTML=datas;
<div id = "greet" ></div>

JavaScript to Output Text Based on User's Current Time

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!
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')
}
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/
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;
}
}
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"))
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")
);
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
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')
}
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";
}
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';
}
<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>
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.
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')
}
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"));
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"
}
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();
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';
}
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.

how to convert date and time to timeago format in jquery

I am trying to display facebook newsfeed and displaying them on mobile web app. It is working fine but the problem is that it does not display time in timeago format(i.e. 2 days ago) on mobile web browser, on the other hand it does display properly on desktop. The format of the date and time is 2011-09-13T11:28:19+0000.
on mobile it displays NaN years ago.
here is my code for timeago function
timeAgo('2011-09-13T11:28:19+0000');
function timeAgo(date_time) {
//to get unix timestamp
var currentDate = Math.round(+new Date()/1000);
var tweetDate = Math.round(+new Date(date_time)/1000);
//alert(tweetDate);
var diffTime = currentDate - tweetDate;
//alert(diffTime);
if (diffTime < 59) return 'less than a minute ago';
else if(diffTime > 59 && diffTime < 120) return 'about a minute ago';
else if(diffTime >= 121 && diffTime <= 3600) return (parseInt(diffTime / 60)).toString() + ' minutes ago';
else if(diffTime > 3600 && diffTime < 7200) return '1 hour ago';
else if(diffTime > 7200 && diffTime < 86400) return (parseInt(diffTime / 3600)).toString() + ' hours ago';
else if(diffTime > 86400 && diffTime < 172800) return '1 day ago';
else if(diffTime > 172800 && diffTime < 604800) return (parseInt(diffTime / 86400)).toString() + ' days ago';
else if(diffTime > 604800 && diffTime < 12089600) return '1 week ago';
else if(diffTime > 12089600 && diffTime < 2630880) return (parseInt(diffTime / 604800)).toString() + ' weeks ago';
else if(diffTime > 2630880 && diffTime < 5261760) return '1 month ago';
else if(diffTime > 5261760 && diffTime < 31570560) return (parseInt(diffTime / 2630880)).toString() + ' months ago';
else if(diffTime > 31570560 && diffTime < 63141120) return '1 year ago';
else return (parseInt(diffTime / 31570560)).toString() + ' years ago';
}
How can I solve this problem?
I had a similar problem and i fixed it using the following function.
function relative_time(date_str) {
if (!date_str) {return;}
date_str = $.trim(date_str);
date_str = date_str.replace(/\.\d\d\d+/,""); // remove the milliseconds
date_str = date_str.replace(/-/,"/").replace(/-/,"/"); //substitute - with /
date_str = date_str.replace(/T/," ").replace(/Z/," UTC"); //remove T and substitute Z with UTC
date_str = date_str.replace(/([\+\-]\d\d)\:?(\d\d)/," $1$2"); // +08:00 -> +0800
var parsed_date = new Date(date_str);
var relative_to = (arguments.length > 1) ? arguments[1] : new Date(); //defines relative to what ..default is now
var delta = parseInt((relative_to.getTime()-parsed_date)/1000);
delta=(delta<2)?2:delta;
var r = '';
if (delta < 60) {
r = delta + ' seconds ago';
} else if(delta < 120) {
r = 'a minute ago';
} else if(delta < (45*60)) {
r = (parseInt(delta / 60, 10)).toString() + ' minutes ago';
} else if(delta < (2*60*60)) {
r = 'an hour ago';
} else if(delta < (24*60*60)) {
r = '' + (parseInt(delta / 3600, 10)).toString() + ' hours ago';
} else if(delta < (48*60*60)) {
r = 'a day ago';
} else {
r = (parseInt(delta / 86400, 10)).toString() + ' days ago';
}
return 'about ' + r;
};
this will help you alot:
someone already did it for you in a jquery plugin
http://timeago.yarp.com/

Categories

Resources