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

The Vue JS Router is prominently displayed in the center of the webpage

I have been delving into Vue JS and working on constructing an app. I've implemented vue router, however, it seems to be causing the content within the routed component to display with excessive margins/padding. I've attempted various solutions s ...

Divs sliding out of alignment

I am experiencing an issue with the scrolling behavior of a wrapper div that contains two nested divs. Specifically, when I scroll the wrapper horizontally on Android devices, the header section and content section seem to be out of sync and there is a not ...

Is there a way to include two functions within a single ng-click event?

Is it possible to incorporate two functions in a single ng-click event? Below is the code snippet: <button class="cButtonSpeichern" ng-click="saveUser()">Speichern</button> In addition, I would like to include this function as well. alert ...

Utilizing either jQuery or Angular, implement a function that adds line breaks after every x characters within

Is there a way to automatically insert a line break every 10 characters in my code? Here is what I have tried so far: Here is the HTML: <div ng-app=""> <textarea id="chat" ng-model="msg"></textarea> <span class="msg" ng-bind="msg" ...

What is the proper sequence for binding jQuery to elements?

I'm currently facing a challenge with using jQuery to link a function to an element. Essentially, I'm loading a series of divs via JSON, with each item in the JSON having an "action" assigned to it that determines which function should be trigger ...

What is the best way to recover accented characters in Express?

Encountering issues with accented characters in my POST request .. I attempted using iconv without success.. Snippet of my code: Edit: ... var bodyString = JSON.stringify(req.body); var options = { host: XXXXX, port: XXX, ...

Encasing common functions within (function($){ }(jQuery) can help to modularize and prevent

As I was creating a global JavaScript function and made some errors along the way, I finally got it to work after doing some research. However, while searching, I came across an example using (function($){ code here }(jQuery); My question is, what exact ...

Launching Angular 2 application on Heroku

Previously, I would combine my Angular 1 and Rails applications and deploy them on Heroku, which always went smoothly. However, now that I've transitioned to Angular 2, I'm looking to segregate my Angular and Rails code. I've successfully cr ...

Include features once JSON has been loaded

Received this JSON data: { "info": [ { "id": 999, "products": [ { "id": 1, }, { "id": 2, } ] } ] } Info -- products -----id Here is the factory code snippet: AppAngular.factory('model', ['$http', f ...

"Enhance user experience with the React Popover feature from Material UI

Looking for help on creating a dynamic color palette with a hover feature for the PaletteIcon. The issue I'm facing is that when I try to select a color, the palette disappears. Is there a specific property I should add to the React component or anoth ...

Drop-down options disappear upon refreshing the page

Code snippet for sending value to server using AJAX in JavaScript In my script, the status value may vary for each vulnerable name. When selecting a status option and storing it in the database through AJAX, the selected value is lost after refreshing th ...

Having trouble getting webpack and babel to start using npm

Greetings, wonderful people of the internet! I am a newcomer to the enchanting world of programming and I am facing a perplexing issue. Although Webpack is trying to guide me towards the solution, I seem to be struggling with fixing it on my own. const pa ...

In my Django html file, I am facing an issue with the IF statement that seems to be dysfunctional

I have a like button and I want it to display an already liked button if the user has already liked the post. Here is my HTML: {% for post in posts %} <div class="border-solid border-2 mr-10 ml-10 mt-3 px-2 pb-4"> & ...

Encountering difficulty in accessing game.html following button clicks

Why isn't the redirection to game.html happening after clicking on the buttons in index.html? The file structure consists of server/server.js, public/index.html,public/game.html. <!DOCTYPE html> <html> <title>QUIZ GAME</title ...

Ensure the form is validated using AngularJS along with an Ajax request

I need help with HTML code <input type="text" name="username"> <label for=""> Email </label> <input type="email" name="email"> My goal is to use AJAX to check if the username and email already exist in the database ...

Exploring the realms of Django Administrator with external JavaScript integration

Currently, I am working with django 2.0 that includes jquery 2.2.3. My goal is to implement the ImageViewer Javascript app (https://github.com/s-yadav/ImageViewer) on one of my admin pages. I have added the necessary js and css files to the Media class wit ...

Achieving a Transparent Flash overlay on a website without hindering its usability (attention, interaction, form submissions, etc.)

Currently, we are attempting to overlay a transparent flash on top of an iframe which loads external websites. Is there a method to configure the page in a way that allows the transparent flash to be displayed while still allowing interaction with the und ...

After being redirected from another page using history() in React, the state is initially set to null but later gets updated to the correct value - Firebase integration

After logging in and being redirected to the profile page, I encounter an error that says 'Unhandled Rejection (TypeError): Cannot read property 'email' of null'. How can I ensure that the state is set before proceeding with any additio ...

The semantic UI search functionality is malfunctioning

My experience with semantic ui involves encountering an issue where the search result on a website appears empty, despite finding the JSON result in my console. This is the JavaScript code I am using: $('.ui.search').search({ apiSettings: { ...

pg-promise received an error due to an incorrect parameter being passed in for options

I have been working on transitioning my files from utilizing the pg package to the pg-promise package. Initially, everything was functioning correctly with the original pg solution I had in place. However, upon switching to pg-promise and referencing the d ...