Check to see if the upcoming birthday falls within the next week

I'm trying to decide whether or not to display a tag for an upcoming birthday using this boolean logic, but I'm a bit confused.

const birthDayDate = new Date('1997-09-20');
const now = new Date();
const today = new Date(now.getFullYear(), now.getMonth(), now.getDate(), 0, 0, 0);
const threshold = new Date(today).setDate(today.getDate() + 8);
console.log(birthDayDate >= today && birthDayDate < new Date(threshold));

This is the code snippet I have and I want it to log true if there's an upcoming birthday within a 7-day window.

As of writing this post in my timezone, today is 09.14.2022. I expect the result to be true because the date we are comparing with is only 6 days away, without considering the years.

Answer №1

How is it possible for a day in 1997 to be considered greater than a day in 2022 when comparing birth dates?

One potential solution is to update the year of the birth date to the current year and then verify if that date falls within 7 days from the present:

const birthDayDate = new Date('1997-09-20');
const thisYear = new Date(birthDayDate)
thisYear.setYear(new Date().getFullYear());
const now = new Date();
console.log(thisYear - now <= 1000 * 60 * 60 * 24 * 7 && thisYear - now >= 0);

1000 * 60 * 60 * 24 * 7 equals 7 days in milliseconds.

We also need to confirm whether the date has already passed by checking thisYear - now >= 0.

Answer №2

Make sure to use this code snippet that includes a check for dates being passed after the birth date, which will result in returning false.

 const birthDayDate = new Date("1997-09-20");
 const now = new Date();

 const after_threshold = new Date(now.getFullYear(),birthDayDate.getMonth(),birthDayDate.getDate(),0,0,0);

 const before_threshold = new Date(now.getFullYear(),birthDayDate.getMonth(),birthDayDate.getDate() + 8,0,0,0);

 console.log(before_threshold >= now && after_threshold <= now);

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

Dealing with HTML and Escaping Challenges in jQuery Functions

Here is a string I have: var items = "<div class='item'><div class='item-img' style='background-image: url('images.123.jpg')'></div></div>" I am looking to update the inner HTML of a div: $ ...

Accessing data from arrays asynchronously using JavaScript

Update I have included actual code below, in addition to the concept provided earlier. Here is the async array access structure I am trying to implement: for (p = 0; p < myList.length ; p++){ for (k = 0; k < RequestList.length; k++){ i ...

Extracting timestamped text data from a simulated chat interface

I am looking to gather chat data from Twitch clips. These are saved moments from livestreams where viewer reactions are captured. Take a look at this example clip: While I can scrape all the data by watching the video and utilizing query selectors, my goa ...

Using Angular to include more than two parameters in an HTTP GET request

Currently, I am developing an application that requires downloading a file upon clicking a button within a template. The screen displays multiple files, each with its own corresponding button. I need to send the index number of the array to Angular and pas ...

Adjust the canvas size to fit its parent element ion-grid

I am currently working on an Ionic 3 component that displays a grid of images connected by a canvas overlay. I have utilized Ionic's ion-grid, but I am facing an issue with resizing the canvas. The problem is that I cannot determine the correct dimens ...

Can you explain the significance of the syntax "require: ^"?

Can someone explain the significance of the ^ symbol under require in this Angular directive code snippet? I came across this code and am having trouble understanding its meaning. .directive('accordionGroupHeading', function() { return { ...

Oops! The requested page "/api/auth/[...nextauth]" is missing the necessary "generateStaticParams()" function, thus making it incompatible with the "output: export" configuration

Currently, I am working on a Next.js project where I have successfully implemented user authentication using next-auth with the Google Provider. However, while attempting to build the project, an error is being thrown by the compiler stating: "Error: Page ...

Every time I navigate to a new page in NextJs, the useEffect hook

I am working on developing a new blog app with Next.js. In the current layout of the blog, I have successfully fetched data for my sidebar (to display "recent posts") using the useEffect/fetch method, as getInitialProps only works on Pages. However, this ...

Tips for preserving dynamically generated HTML through Javascript during page reload

I have a straightforward question, but I haven't been able to find a suitable answer. Here's my situation: On my HTML page, I have a form. Using jQuery and AJAX, I submit the form and then use some JavaScript code to change the content of a spec ...

Using React Refs to Trigger the video.play() Method - A Step-by-Step Guide

Is there a way to use a ref in order to trigger video.play()? Currently encountering an error: preview.bundle.js:261916 Uncaught TypeError: _this2.videoRef.play is not a function Take a look at my component: import React from 'react'; import s ...

How can I update getServerSideProps using a change event in Next.js?

Currently, I am faced with the task of updating product data based on different categories. In order to achieve this, I have set up an index page along with two components called Products and Categories. Initially, I retrieve all products using the getServ ...

Unable to stop interval in Angular 5 application

My setInterval() function seems to be working fine as the timer starts, but I am encountering an issue with clearInterval(). It does not stop the timer when the counter value reaches 100 and continues running continuously. Any help or suggestions would be ...

Troubleshoot: Bootbox Confirm Functionality Issues

Can anyone help me troubleshoot this issue? I'm trying to implement code that uses bootbox.confirm when deleting a file, but it's not functioning correctly. $('#fileupload').fileupload({ destroy: function (e, data) { var that = $(th ...

Modifying the href attribute of links within various occurrences of an element using jQuery based on its content

Here is an illustration of a recurring element on a webpage <td class=" market all"> <a href="linktosomesite?param=123" target="_blank">123</a> </td> Similar elements change the parameter, resulting in links like: <td clas ...

The custom validation function in jQuery is not triggering

I am facing an issue with my HTML and JavaScript setup, which looks like this: <html> <head> <title>Validation Test</title> <script src="https://code.jquery.com/jquery-3.4.1.js"></script> <script src="htt ...

Having trouble getting two components to return in React

After successfully implementing the Hello World example by returning "Hello" and "world" from two different components, I encountered a problem with my code. In this specific code snippet, I am unable to return the Menubar component, although the Map compo ...

Error: Access Denied - discord.js bot command cannot be executed due to lack of authorization

Every time I initiate the bot and try to execute my "ping" command, an error occurs: js:350 throw new DiscordAPIError(data, res.status, request); ^ DiscordAPIError: Missing Access at RequestHandler.execute (C: ...

How to assign a click event to dynamically generated HTML elements using jQuery

My goal is to attach an onclick event to a dynamically inserted element using jQuery However, I am facing an issue where the function does not execute. I would appreciate it if someone could help me determine why this example is not functioning correctly ...

Leveraging React Native to position a view absolutely in the center of the screen without obstructing any other components

How can I center an image inside a view in the middle of the screen using position: "absolute"? The issue is that the view takes up 100% of the width and height of the screen, causing all components underneath it (such as input fields and buttons ...

How can I display a PHP variable in JavaScript?

I am having trouble displaying a PHP variable in Javascript; Below is the code I am using: <script type="text/javascript> $(document).ready(function (){ var n=<?php echo json_encode($count)?>; for(var i=0;i<n;i++){ var div ...