Depending on the time of the day. I am trying to display Morning, Afternoon or Evening to the user using the JavaScript ( new Date() ) method. But what I am receiving in response is just the (else) statement. Can I get advice as to what I am doing incorrectly?
const mainHeader = document.getElementById("header");
var greetings = () => {
var today = new Date();
}
window.onload= (e) => {
greetings;
if(today >= 1 && today < 12) {
mainHeader.innerHTML = "<h3>Good Morning! And Welcome To Guess The Number</h3>"
console.log("Morning: between 1 and 12");
} else if(today >= 12 && today < 17) {
mainHeader.innerHTML = "<h3>Good Afternoon! And Welcome To Guess The Number</h3>"
console.log("Afternoon: between 12 and 17");
} else if(today >= 17 && today <= 24) {
mainHeader.innerHTML = "<h3>Good Evening! And Welcome To Guess The Number</h3>"
console.log("Evening: between 17 and 24");
} else {
mainHeader.innerHTML = "<h3>Welcome to Guess The Number</h3>"
console.log("No time zone");
}
}
You need to return the hour from greetings(), and then assign it to a variable in the window.onload function.
const mainHeader = document.getElementById("header");
var greetings = () => {
var today = new Date();
return today.getHours();
}
window.onload = (e) => {
var today = greetings()
if (today >= 1 && today < 12) {
mainHeader.innerHTML = "<h3>Good Morning! And Welcome To Guess The Number</h3>"
console.log("Morning: between 1 and 12");
} else if (today >= 12 && today < 17) {
mainHeader.innerHTML = "<h3>Good Afternoon! And Welcome To Guess The Number</h3>"
console.log("Afternoon: between 12 and 17");
} else if (today >= 17 && today <= 24) {
mainHeader.innerHTML = "<h3>Good Evening! And Welcome To Guess The Number</h3>"
console.log("Evening: between 17 and 24");
} else {
mainHeader.innerHTML = "<h3>Welcome to Guess The Number</h3>"
console.log("No time zone");
}
}
<div id="header">
</div>
You never define today in the onload function(even if you called greeting, today wouldn't be defined b/c var is function scoped). Instead replace greetings; with var today = new Date().getHours(); and remove the greetings function.
If you still want to keep greetings as a function, you can replace it with var greetings = ()=>new Date().getHours(); and replace greetings; with var today= greeting();
Related
I tried the code below but it didn't work.
var hour = new Date().getHours();
var min = new Date().getMinutes();
if (hour >= 11 && hour <= 12 && min < 40 && min > 20) {
document.body.style.background = "green";
} else {
document.body.style.background = "red";
}
you had three problems here:
the extra } at the end
hours is not defined. I changed it to hour, which is defined
'=>': this is not necessary for the hours. since you are only checking two hours (11 and 12), it's much simpler to check each hour and it's minuets separately.
var hour = new Date().getHours();
var min = new Date().getMinutes();
if((hour == 11 && min >40) || hour == 12 && min < 20) {
document.body.style.background = "red";
} else {
document.body.style.background = "green";
}
This is just for this example.
var hour = new Date().getHours();
var min = new Date().getMinutes();
if (hour >= 11 && hour <= 12 && (hour === 11 ? min > 40 : min < 20)) {
document.body.style.background = "red";
} else {
document.body.style.background = "green";
}
You can use the javascript Date object and compare with the Date object between start time, end time and current time.
const date1 = new Date();
date1.setHours(11);
date1.setMinutes(40);
const date2 = new Date();
date2.setHours(12);
date2.setMinutes(20);
const today = new Date();
if (today >= date1 && today <= date2) {
document.body.style.background = "red";
} else {
document.body.style.background = "green";
}
Your logic had some problems so I fixed them. This will change background to red if between the hours of 11:40 AM and 12:20 PM (inclusive):
var hour = (new Date()).getHours();
var min = (new Date()).getMinutes();
if (hour == 11 && min >= 40 || hour == 12 && min <= 20) {
document.body.style.background = "red";
} else {
document.body.style.background = "green";
}
Hello i want to change the body Background color on specific time with JavaScript but the code don't seems to work! Why?
function changebg(){
var date= new Date().getHours();
if(date >= 21 && date <=6){
document.body.style.backgroundColor="black";
}
}
changebg();
Probably you can try with date >= 21 || date <= 6 instead.
changeBackground();
function changeBackground() {
const currentHour = new Date().getHours();
if(currentHour >= 21 || currentHour <= 6) {
//document.body.style.backgroundColor="black";
console.log('now you can change the color here for night');
} else {
console.log('default color');
}
}
Try this :
function changebg(){
var date= new Date().getHours();
if(date >= 9 || date <=6 ){
document.body.style.backgroundColor="black";
}else{
//
}
}
changebg();
You are probably want something like this:
function changebg(){
var hour = new Date().getHours();
if (hour >= 21 || hour <= 6) {
document.body.style.backgroundColor="black";
}else{
// todo
}
}
changebg();
I have created this to check if time is between 17:00 / 23:00.
This works fine! But now I want to check if its weekend.
Can you help me?
var objDate = new Date();
var hours = objDate.getHours();
if (hours >= 17 && hours <= 23) {
document.write('<!--test1 -->');
}
else {
document.write('<!--test2 -->');
}
Use the getDay() method of the Date object (0 corresponds to Sunday and 6 to Saturday):
<script language="javascript">
var objDate = new Date();
var hours = objDate.getHours(),
dayOfWeek = objDate.getDay();
if(hours >= 17 && hours <= 23 && (dayOfWeek == 6 || dayOfWeek == 0)){
document.write('<!--test1 -->');
} else {
document.write('<!--test2 -->');
}
</script>
var objDate = new Date();
var hours = objDate.getHours();
var n = objDate.getDay();
if(hours >= 17 && hours <= 23){
alert('<!--test1 -->');
}
else{
alert('<!--test2 -->');
}
if(n == 0 || n == 6)
{
alert('Weekend');
}
else
{
alert('Weekday');
}
Ok so what the title says. I am doing this on a server, so I get the server's time using some PHP code. The problem is that it is a time frame without exact round hour values. Should I use nested if else statements?
var serverTimestampMillis = <?php print time() * 1000 ?>;
var checkInterval = 1000;
var checkTime = function () {
serverTimestampMillis += checkInterval;
var now = new Date(serverTimestampMillis);
var timeDiv = document.getElementById('timeDiv');
var messageDiv = document.getElementById('messageDiv');
timeDiv.innerHTML = now.toString();
var dayOfWeek = now.getDay(); // 0 = Sunday, 1 = Monday, ... 6 = Saturday
var hour = now.getHours(); // 0 = 12am, 1 = 1am, ... 18 = 6pm
var minutes = now.getMinutes();
// check if it's Monday to Thursday between 8:30am and 6:30pm
// this is where I don't know how to check 8:30
if (dayOfWeek > 0 && dayOfWeek < 5 && hour > 8 && hour < 18) {
messageDiv.innerHTML = 'Yes, we are open!';
messageDiv.className='open';
}
else {
messageDiv.innerHTML = 'Sorry, we\'re closed!';
messageDiv.className='closed';
}
};
// check the time every 1000 milliseconds
setInterval(checkTime, checkInterval);
checkTime();
thank you in advance, and sorry for being a noob
Compare between two dates using a helper function:
function createDateTime(time) {
var splitted = time.split(':');
if (splitted.length != 2) return undefined;
var date = new Date();
date.setHours(parseInt(splitted[0], 10));
date.setMinutes(parseInt(splitted[1], 10));
date.setSeconds(0);
return date;
}
var startDate = createDateTime("8:30");
var endDate = createDateTime("17:30");
var now = new Date();
var isBetween = startDate <= now && now <= endDate;
console.log(isBetween);
JSFIDDLE.
You can just nest your statements, like you said (to make it easier to read), and then check the specific edge cases (8:30-9 and 18:00-18:30).
if (dayOfWeek > 0 && dayOfWeek < 5) {
if ((hour > 8 && hour < 18) ||
(hour == 8 && minutes >= 30) ||
(hour == 18 && minutes <= 30)) {
messageDiv.innerHTML = 'Yes, we are open!';
messageDiv.className='open';
}
}
I am looking to show an estimated delivery date on the product page for each delivery option we have. I have read through the code in Shopify Variants by Steph Sharp which would work brilliantly except we would need it to be fixed to the current day up until 3pm and then switch to the next working day after 3pm. (Basically taking away the option for the customer to choose the dispatch day.)
I can’t quite get it to work by butchering this code into our template. This is what I have butchered together which seems to work okay but rather than have MON, TUE, WED, … I want to set them as the future dates. Any advice?
EDIT: Also I heard Palec is after using a timer code with this code too. So I will add that in.
<script language="JavaScript">
function day(a) {
var date = new Date();
var days = ["Mon","Tue","Wed","Thur","Fri","Mon","Tue","Wed","Thur","Fri","Mon","Tue","Wed","Thur","Fri"];
var today = date.getDay();
if (today == 1) today = 0; //Monday
if (today == 2) today = 1; //Tuesday
if (today == 3) today = 2; //Wednesday
if (today == 4) today = 4; //Thursday
if (today == 5) today = 5; //Friday
if (today == 6) today = -1; //Saturday Moved To Monday
if (today == 0) today = -1; //Sunday Moved To Monday
h = date.getHours();
if (h <= 9) h = "0" + h;
time = h;
if (time > 15) today++;
var expected = today + a;
var main = days[expected];
document.write('STANDARD DELIVERY ESTIMATE: ');
document.write(main);
}
</script>
<body>
<script language="JavaScript">
day(1)
</script>
I would try something like this:
function day(a) {
var date = new Date();
var hours = date.getHours();
// If after 3pm, add 1 day
if(hours > 15) a++;
var expectedDeliveryDate = addWeekdays(date, a);
document.write(expectedDeliveryDate.toDateString() + ' with Standard Delivery');
}
function addWeekdays(fromDate, days) {
var count = 0;
while (count < days) {
fromDate.setDate(fromDate.getDate() + 1);
if (fromDate.getDay() != 0 && fromDate.getDay() != 6) // Skip weekends
count++;
}
return fromDate;
}
(The code in the addWeekdays function is from this answer on Stack Overflow.)
This code just displays the day name (like the code in your question), but you can format expectedDeliveryDate however you want.
EDIT: I updated my code to use expectedDeliveryDate.toDateString() as specified in the comments. Note that you no longer need the days array or expectedDeliveryDay variable. (You've still got them in your answer but they're not being used.)
This is my final code, based on Steph Sharp’s answer.
function day(a) {
var date = new Date();
var hours = date.getHours();
// If after 3pm, add 1 day
if (hours >= 15) a++;
var expectedDeliveryDate = addWeekdays(date, a);
document.write(expectedDeliveryDate.toDateString() + ' with Standard Delivery');
}
function addWeekdays(fromDate, days) {
var count = 0;
while (count < days) {
fromDate.setDate(fromDate.getDate() + 1);
if (fromDate.getDay() != 0 && fromDate.getDay() != 6) // Skip weekends
count++;
}
return fromDate;
}
Also added a timer:
function ShowTime() {
var now = new Date();
var hrs = 15 - now.getHours();
if (hrs < 0) hrs += 24;
var mins = 60 - now.getMinutes();
var secs = 60 - now.getSeconds();
timeLeft = "" + hrs + ' hours ' + mins + ' minutes ' + secs + ' seconds';
$("#countdown").html(timeLeft);
}
var countdown = setInterval(ShowTime, 1000);
function StopTime() {
clearInterval(countdown);
}