Issue with Javascript Date and Time Validation

My application includes code that is supposed to display HTML pages based on today's date and the time of day (morning, afternoon, or evening). However, it seems like there is an issue with how the time is being checked. Currently, at 2:53pm, only the morning HTML page is being displayed. I attempted to use `console.log` for debugging but got no output, which may be related to Wikitude.

The function responsible for getting today's date is functioning correctly; it's just the time comparison that's not working as expected.

var inputDate = new Date("5/17/2018");

    // Get today's date
    var todaysDate = new Date();

      // call setHours to take the time out of the comparison
      if(inputDate.setHours(0,0,0,0) == todaysDate.setHours(0,0,0,0)) {
          var hour = new Date().getHours();

          console.log("hour is: " + hour);
                    // between 12 PM and 7 AM respectively
            if(hour >= 7 && hour < 12) {
                //morning   (Always running code here no matter what time of day) 
            }
            else if(hour >= 12 && hour <= 18) {
               //afternoon   
            }   
            else {

            //evening or before 7
            }
      }
      else{
           //not today (works if date is not today)
      }

Answer №1

You made a mistake in the if statement: Instead of using =>, it should be >=

var inputDate = new Date("5/17/2018");

// Fetch today's date
var todaysDate = new Date();

// Using setHours to remove the time from the comparison
if (inputDate.setHours(0,0,0,0) == todaysDate.setHours(0,0,0,0)) {
  var hour = new Date().getHours();

  console.log("hour is: " + hour);
  // between 12 PM and 7 AM respectively
  if (hour >= 7 && hour < 12) {
    // Good morning (Code always displayed here)
    alert('morning')
  }
  else if (hour >= 12 && hour <= 18) {
    // Good afternoon
    alert('afternoon')
  }   
  else {
    // Evening or before 7
    alert('evening')
  }
}
else {
  // Not today
  alert('not today')
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Switching from constructors to Hooks in REACT

I am currently working on adding a modal example within a function in my project. I have a specific requirement to incorporate hooks instead of using the constructor in a class-based component. This is the code snippet with the class-based implementation: ...

Observing the element with a directive

I am working with the following code: angular.module("Test", []) .directive("testDirective", function () { return { restrict: "A", scope: { model: "=" } link: function(scope, element) { scope.$watch(function () { elem ...

Guide on how to turn off cache in AngularJS + NodeJS CRUD application

I'm encountering an issue with cache in Internet Explorer, but everything seems to be working fine in Chrome. Whenever I try to add an item in my application, the data doesn't refresh automatically and I have to press Ctrl+R to manually refresh. ...

Tips for iterating through an array of images and displaying them in a React component

I am working on a project in my react app where I have 5 images that I want to cycle through indefinitely. The goal is to create an animation where a light bar appears to be constantly moving. The shifting dot in each image will give the illusion of movem ...

Attempting to develop a worldwide npm package. Upon running my script, I encounter the message "The designated path cannot be found."

I have been working on converting my npm module into a global command. You can find the code at this link. However, when I try to run $ seed, an error stating "The system cannot find the path specified" is displayed, indicating that it recognizes it as a ...

Error encountered when WebDriverIO attempted to connect to Appium due to a lack of compatible capabilities

I'm currently facing an issue while attempting to link my virtual Android Device through Appium with my Webdriverio script for the purpose of automating some testing tasks. Here are the capabilities that I have set: capabilities: [{ // N ...

Tips for assigning a value in a dropdown menu with AngularJS

Can someone help me with setting the same value in multiple drop-down lists using angular.js? Below is an explanation of my code. <table class="table table-bordered table-striped table-hover" id="dataTable"> <tr> <td width="100" align ...

Guide: Highlighting a selected link in Navigation without redirecting the page can be achieved in AngularJS by utilizing

I have a list of links that I want to be able to highlight when clicked without redirecting to the page. Below is the code snippet: HTML <ul class="nav nav-list"> <li ng-repeat="navLink in navLinks" ng-class="navClass('{{navLink.Title ...

What is the best way to create an array containing dictionaries?

Hey there, I'm having an issue with my React.js code. Here's what I have: const array1 = [1, 4]; const map1 = array1.map(x =>{'x2': x * 2, 'x3': x * 3}); console.log(map1); // expected output: Array [{'x2': , 1, ...

Exploring the power of Vue.js by utilizing nested components within single file components

I have been attempting to implement nested single file components, but it's not working as expected. Below is a snippet of my main.js file : import Vue from 'vue' import BootstrapVue from "bootstrap-vue" import App from './App.vue&apos ...

Collaborative real-time text editing tool for Angular on ASP.NET with multi-user functionality, powered by

I'm interested in integrating support for multiple contributors similar to Google Docs into my AngularJS 1.x application which has an ASP.NET MVC backend. Considering how SignalR is becoming outdated and with Office Online enabling real-time collabora ...

Unable to bring in openai on Node.js

I recently installed Node version 16.13.1 and globally installed the openai package using 'npm install -g openai'. In my script, I imported the necessary packages like this: const { Configuration, OpenAIApi } = require('openai') Howeve ...

What are the implications of storing data on the browser in the form of a JavaScript array?

Below is the code I have written: var back_arr = [], forward_arr = [], i = 1; $('button').on('click', function(){ var new_value = $('input').val(), old_value = $('.content').html(); i = i + 1; ...

Updating ngModel using the value retrieved from a service call

After experiencing dissatisfaction with Angular's form validation, I decided to develop my own solution. However, I have encountered a perplexing issue that has me at a loss. Here is how my setup looks: I employ a directive to create a new form. Th ...

The Ionic tab is already finished displaying even before the data has completed loading

Creating a favorites section for a vouchers app has proven to be slightly challenging. When attempting to retrieve the current user's favorite vouchers and display them using ngFor in the HTML, I encountered an issue. The very first time I open the fa ...

Error: Unable to assign a value to the statusCode property because it

During the development of my application backend, I encountered an error while working on the user login route. When testing the route using Postman, I received the following error message: UnhandledPromiseRejectionWarning: TypeError: Cannot set propert ...

Ways to encounter the "10 $digest() iterations reached. Aborting" issue in Jasmine

There have been inquiries regarding how to handle the error message: 10 $digest() iterations reached. Aborting, One example is found in a question on Stack Overflow (here). The solution involves modifying the code to prevent changes to the $scope durin ...

Combining Flask with Ajax: AttributeError - WSGIRequestHandler does not have the attribute 'environ'

Currently, I am working on using ajax to trigger the execution of a Python file that continuously monitors changes in a text file. If any changes are detected, it will communicate back to ajax for further actions. The Python script must start running as so ...

Comparison Between Angular and Web API in Regards to Racing Condition with Databases

Currently, I am working on an Angular service that iterates through a list and makes web API calls to add or modify records in the database. The service operates on a small record set with a maximum of 10 records to update. After the loop completes, Angula ...

Struggling to adjust the quantity of items in a basic shopping cart when adding multiples of the same item

Hello there! I'm currently working on a project where I need to increase the quantity of each item added to the cart if it's already in there. This is actually my first time posting, so any tips on asking better questions would be greatly appreci ...