Arranging by upcoming birthday dates

Creating a birthday reminder app has been my latest project, where I store names and birthdays in JSON format. My goal is to display the names sorted based on whose birthday is approaching next.

Initially, I considered calculating the time until each person's birthday by subtracting the current day and month from their birthday. However, this approach raised concerns about handling negative results and edge cases such as December. I'm hoping there might be a simpler solution out there that I haven't considered yet.

If you'd like to take a look at the base working code, here is a link to the plunkr: http://plnkr.co/edit/AkP6FRRG917TDdTtfWM7?p=preview

Answer №1

To follow the advice of others, you can change the string into a unix timestamp or date format.

For an updated Plunker example, check it out here.

This controller includes a new variable called fromNow in the data:

$scope.friends.forEach(function(data){
      var day = data.birthday.split("/")
      var currentYear = new Date().getFullYear();
      var birthdayDate = new Date(currentYear, day[0] - 1, day[1])
      var now = new Date().valueOf();
      if (birthdayDate.valueOf() < now){ 
          birthdayDate.setFullYear(currentYear+1)
      }
      data.fromNow = birthdayDate.valueOf() - now;
})
  1. Break down the date and month components into individual parts (forming a list like ["02","14","1985"])
  2. Create a date object using the current year, the month day[0], and the day day[1]. (Remember to subtract 1 from the months due to Javascript's 0-based system).
  3. Obtain a numerical value for the present date/time
  4. If the birthday has already passed, add one more year
  5. Assign the number of milliseconds between the current time and the birthday to the variable fromNow

You may need to adjust this code so that birthdays happening today are not moved a year ahead, keeping them at the end of the list.

Additionally, I have included quotes around the orderBy parameter:

<tr ng-repeat="friend in friends| orderBy:'fromNow' ">

Answer №2

To tackle this issue, my approach would involve converting the dates into Unix timestamps (integer values) and then performing a straightforward sorting operation on them.

One way to convert a date to a timestamp is by utilizing JavaScript's Date.parse() method.

Answer №3

Find the UNIX timestamps for the current date and birthdate and evaluate their differences to determine which one is closer to the present moment

birthdates = [new Date(1988,01,27), new Date(2013,01,01)];

birthdates.sort(function(firstDate,secondDate){

    //calculate the difference between first date and current date
    firstDifference = new Date() - firstDate;

    //calculate difference between second date and current date.
    secondDifference = new Date() - secondDate;

    //return the smallest value.
    return firstDifference - secondDifference;

});
//display the sorted array.
alert(birthdates);

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

Integration of elFinder with TinyMCE 4

Has anyone attempted to integrate elFinder into the latest version (4b1) of TinyMCE? The previous implementation seems to be not working. If you have any snippets or tips, please share. Thank you very much. ...

Adding a script to the head of a Next.js page by using the Script component

I need assistance with inserting tracking code from Zoho application into the Head section of each page in my Next.js application. I am currently using a _document.tsx file and following the instructions provided by Next.js regarding the use of the Next.js ...

WooCommerce Checkout and My Account Edit Address now feature dynamic selectable fields for improved customization options

After finding a solution on Stack Overflow to show sub Areas dropdown based on the selected city in WooCommerce checkout, I customized the code for my specific requirements: function cities_areas_settings() { $text_domain = 'woocommerce'; ...

Utilizing directives while initiating dynamic components

I've been exploring the capabilities of dynamically creating components using the ComponentFactoryResolver. const factory = this.componentFactoryResolver.resolveComponentFactory(FooComponent); const component = this.templateRoot. ...

Converting text to JSON using JSONP with jQuery's AJAX functionality

Potential Duplicate Question 1 Possible Duplicate Inquiry 2 I have been searching for a definitive explanation on JSONP across various questions but haven't been able to find one yet. For instance, I am attempting to make a cross domain request us ...

Editing HTML using the retrieved jQuery html() content

I need to modify some HTML that is stored in a variable. For example: var testhtml = $('.agenda-rename').html(); console.log($('input',testhtml).attr('name')); I also tried the following: console.log($(testhtml).find(' ...

Combining Option Value and Name Selection Using React Hooks

Currently, I am facing a situation where I need to retrieve two different values (item.id and item.name) to set the State when selecting an item from my dropdown menu. Right now, I am only able to do this for one value (item.id). Is it possible to achieve ...

Encountering the error message "Unexpected token export" while attempting to implement the "framer-motion" package with Webpack

My experience with NextJS has been smooth sailing until now. I recently added the "framer-motion" module to animate some components, and it caused a major issue. Whenever I navigate to a page containing the import statement: import { motion } from "fr ...

The error message encountered is "Uncaught (in promise) Error: Unable to access attributes of an undefined object (reading 'launch')."

I am currently learning electron.js by developing a basic application that extracts information from a website. However, I am encountering a frustrating and annoying error. Here is the folder structure of my project The following code snippet represents ...

What can be done to prevent Leaflet from processing markers that fall outside of its bounding box?

I recently set up a Leaflet map with GeoDjango and rest_framework_gis, but I am facing issues with limited results and pagination. The map seems to process every marker it receives cumulatively, leading to lagging and browser crashes. I was advised in a co ...

Utilizing the express framework to dynamically render route requests

I'm interested in trying dynamic routing with the express framework for my Node.js server. Here is an example of how I am attempting to achieve this: <a href="/views/adminpanel?url={{mMenu.WebAddress}}" ng-click="Description(mMenu.WebAddress)"> ...

What is the solution to resolving the warning about the router no longer defaulting the history prop to hash history?

I have implemented browser history in my code within routes.js export default ( <Router history={browserHistory}> <Route path="/" component={Main}> <Route path="home/:username" component={Home}> <IndexRoute co ...

Creating types for React.ComponentType<P> in Material-UI using TypeScript

I am currently working with Typescript and incorporating Material-UI into my project. I am trying to define the component type for a variable as shown below: import MoreVert from '@material-ui/icons/MoreVert' import { SvgIconProps } from '@ ...

How can I effectively address issues with jqGrid's sorting and paging functionality?

After making changes to the server-side code, it now looks like this: int nm = objects.ToList().Count; if (objects.ToList().Count > 0) return new PagedList(objects, nm, 1, 25, null); else return null; The JSON data has been updated as follows ...

Call order for importing and exporting in NodeJS

This question is related to "code theory." Let's explore a scenario where I am utilizing the global namespace in a package. The structure includes a main entrypoint file, classes that are exported, and utility files used by the classes. Here's a ...

Examining the contents of an array in JavaScript

I am currently conducting API testing. My objective is to verify the presence of a specific name within the API response. The data from the API response is structured in an array format. Despite my intention to check for the existence of the name "activ ...

What steps can be taken to resolve the error message "Module '../home/featuredRooms' cannot be found, or its corresponding type declarations"?

Upon deploying my site to Netlify or Vercel, I encountered a strange error. The project runs smoothly on my computer but seems to have issues when deployed. I am using TypeScript with Next.js and even attempted renaming folders to lowercase. Feel free to ...

The v-autocomplete feature in vuetify doesn't allow for editing the text input after an option has been selected

Link to code on CodePen: CodePen Link When you visit the provided page and enter "joe" into the search box, choose one of the two Joes that appear. Try to then select text in the search box or use backspace to delete only the last character. You will no ...

Vue's watch function failing to trigger

Experiencing issues with Vue watch methods not triggering for certain objects even when using deep:true. Within my component, I am passed an array as a prop containing fields used to generate forms. These forms are dynamically bound to an object named cru ...