AngularJS - A Guide to Determining the Time Span Between Two Dates

I am trying to figure out the exact number of months and days between two specific dates.

For example, if the start date is "Jan 12, 2014" and the end date is "Mar 27, 2017", the result should be "38 months and 15 days".

However, I am currently only able to calculate the total number of days between the start and end dates. I need assistance in determining the months and days in between.

Additionally, I would like to know how to divide the 15 days by the total number of days in the end-date month.

If anyone could provide some guidance, I would greatly appreciate it as I am new to working with date functions.

var date = new Date();
            console.log("date: "+date);
            var currentDate = $filter('date')(date, "yyyy-MM-dd HH:mm:ss");

            $scope.userdob = "2017-01-29";
            var dobdate = $filter('date')($scope.userdob, "yyyy-MM-dd HH:mm:ss");

            console.log("dob: "+dobdate);

            /* differentiate Date */            
            var date1 = $filter('date')($scope.userdob, "yyyy-MM-dd");
            var date2 = $filter('date')(date, "yyyy-MM-dd");

            date1 = date1.split('-');
            date2 = date2.split('-');

            date1 = new Date(date1[0], date1[1], date1[2]);
            date2 = new Date(date2[0], date2[1], date2[2]);

            var date1_unixtime = parseInt(date1.getTime() / 1000);
            var date2_unixtime = parseInt(date2.getTime() / 1000);

            var timeDifference = date2_unixtime - date1_unixtime;
            var timeDifferenceInHours = timeDifference / 60 / 60;
            $scope.timeDifferenceInDays = timeDifferenceInHours  / 24;
            console.log("timeDifferenceInDays: "+$scope.timeDifferenceInDays);

Answer №1

Here is a useful function for calculating months:

function calculateMonths() {
  var currentDate = new Date();
  var targetDate = new Date('2013', '02', 12);
  var yearsDifference = currentDate.getFullYear() - targetDate.getFullYear();
  var monthsDifference = currentDate.getMonth() - targetDate.getMonth();
  var totalMonths = (yearsDifference * 12) + monthsDifference;
  var currentDateDay = currentDate.getDate();
  var targetDateDay = targetDate.getDate();
  var daysDifference = currentDateDay - targetDateDay;
  var lastDayCurrent = null;
  var lastDayTarget = null;
  if(daysDifference < 0) {
      var lastDayCurrent = new Date(currentDate.getFullYear(), currentDate.getMonth() + 1, 0).getDate();
      var lastDayTarget = new Date(targetDate.getFullYear(), targetDate.getMonth() + 1, 0).getDate();
      if(currentDateDay != lastDayCurrent || targetDateDay != lastDayTarget) { 
          totalMonths -= 1;          
          daysDifference = (new Date(targetDate.getFullYear(), targetDate.getMonth() + 1, 0).getDate()) + daysDifference;
      } else {
          daysDifference = 0;
      }
  }
  console.log(totalMonths);
  return totalMonths;
}

Answer №2

It's possible that my understanding is off, but shouldn't the code snippet look something like this:

const monthsDifference = date2.getMonth() - date1.getMonth();
const daysDifference = date2.getDate() - date1.getDate();
let yearsDifference = date2.getYear() - date1.getYear();
    monthsDifference += 12 * yearsDifference;

if(daysDifference < 0){
       monthsDifference -= 1;
       const daysInPreviousMonth = new Date(date2.getYear(), date2.getMonth() - 1, 0).getDate();
       daysDifference = daysInPreviousMonth + daysDifference;
}
console.log('The difference between the two dates is ' + monthsDifference + ' months and ' + daysDifference + ' days');

Best regards, Alex

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

Interactive Content Swapping: How to Use Javascript for Dynamic Link Updates

http://jsfiddle.net/bUjx7/42/ <script type='text/javascript' src='http://code.jquery.com/jquery-1.9.1.js'> </script> <script type='text/javascript'> $(document).ready(function () { $('.fieldreplace ...

Encountering a connection error when trying to access a Google spreadsheet within a Next.js application

I am currently exploring Next.js and attempting to utilize Google Sheets as a database for my project. Although my application is functioning correctly, there is still an error message displaying that says "not forgot to setup environment variable". I have ...

React App anchor tag's external links fail to function properly on subsequent clicks when accessed through mobile devices

I have encountered an unusual issue with <a> anchors for external links in my React App on mobile viewports. Initially, clicking an external link opens a new tab just fine on mobile. However, subsequent link clicks on the same or other <a> elem ...

Leveraging the power of angular's $asyncValidators by implementing a cache

I've created a validation directive that verifies a value against an endpoint App.directive('validate', function(fooService, $q) { return { restrict: "A", require: "ngModel", link: function(scope, elem, attrs, ngModel) { ...

The onEnter and onExit functions within a React Native Component using react-native-router-flux

Within my app's router definitions, I have successfully utilized the onEnter/onExit method at the root level: <Scene key="arena" hideNavBar={true} onEnter={() => console.log("Entered")} component={ArenaPage} /> Is there a way to achieve th ...

Issue with uploading files on Android devices in Laravel and Vue JS

My Laravel/Vue JS web app allows users to upload files and photos. Everything runs smoothly except when accessed on Android devices, where the axios call seems to get stuck indefinitely. Below is the code snippet causing the issue: Vue JS component <t ...

Donut and Bar Graph by Highchart

My goal is to create a chart similar to the one shown in the Example Image linked below. I have provided two separate plunkers for each type of chart. What I am aiming for: Example Image Donut Chart: ===> Refer to Comment section for Plunkr link // ...

Is it possible for me to repurpose the existing REST API and database?

My website is built with angularjs, html, and a rest api on the backend, using mysql as the database. Now I want to convert it into an app and am considering using phonegap. Is it possible to use the same database and rest api for developing the app? ...

Error encountered in onclick handler due to unterminated string literal in PHP and jQuery

Trying to utilize PHP to send variables into the onclick of an element is resulting in an "Unterminated string literal" error due to long strings. Below is a snippet of my PHP code: $query = $conn->prepare("SELECT Name, Image, Description, Link, Price, ...

React Native error - "Invalid element type: expected a string or class/function, but received undefined" - encountering issue with importing a custom library?

Alright, I'm looking to make some modifications to this library, so I am attempting to import the non-transpiled version by downloading the repository and importing it from here: https://github.com/nicotroia/react-native-floating-action-menu#readme A ...

The intricacies of converting AudioBuffers to ArrayBuffers

I currently have an AudioBuffer stored on the client-side that I would like to send through AJAX to an express server. This link provides information on how a XMLHttpRequest can handle sending and receiving binary data in the form of an ArrayBuffer. In m ...

converting HTML values to TypeScript

I'm a beginner with Angular and could use some assistance. Currently, I have two components - one for the index and another for navigation. Within the index component, there are subcomponents that change based on the value of a variable called produ ...

What is the best choice between .dot template and Angular for this situation?

Looking for some guidance on where to invest my time, rather than ready-to-use code. Curious about integrating Angular (1.4.3) features into an express (4) application that currently uses .doT templates. Is it possible to work with both .doT templates an ...

Looking for a solution to toggle the visibility of a div based on whether search results are found or not using JavaScript

Running this code <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Searc ...

Ways to avoid the CSS on the page impacting my widget?

Currently working on a widget using JavaScript and avoiding the use of iframes. Seeking assistance on how to prevent the styles of the page from affecting my widget. Initially attempted building it with shadow DOM, but ran into compatibility issues with ...

Guide on creating dynamic datasets and multiple dynamic yAxes

To enhance my chart, I am interested in adding multiple Y Axes based on the examples provided below: script 1 script 2 Although I attempted to modify the code as shown below, it seems to not be functioning properly. function rdnum() { return Math.flo ...

Using an AngularJS directive to trigger a function with ng-click

Everything is working well with my directive, but I would like to utilize it within ng-click. Unfortunately, the function inside the link is not getting triggered. Here's the link to the code snippet. <div ng-app="editer" ng-controller="myCtrl" ...

"Troubleshooting the issue of Angular's select binding causing a disruption

The Angular version being used is 1.4.7. Within the model in question, there are two objects: 'systems', which is an array, and 'selectedSystem'. The desired outcome is for 'selectedSystem' to reference one of the objects wit ...

The issue arises when React child props fail to update after a change in the parent state

Here's the main issue I'm encountering: I am opening a websocket and need to read a sessionId from the first incoming message in order to use it for subsequent messages. This should only happen once. I have a child component called "processMess ...

The share-modal.js file is throwing an error because it is unable to read properties of null, particularly the 'addEventListener' property, at

I encountered an error that I want to resolve, but it's proving to be quite challenging. Despite extensive searching on Google, I haven't found a solution yet. Uncaught TypeError: Cannot read properties of null (reading 'addEventListener&apo ...