Distinguishing the time gap between two dates in AngularJS

My application consists of an API built using Spring Boot and a view created with AngularJS. The app retrieves a report indicating when an incident started and ended, with examples like startdate(2015-12-01T08:19:00.000Z) and enddate(2015-12-06T02:59:00.000Z).

I'm struggling to find an efficient way to calculate the time difference between these two dates and assign it to a new variable called "unavailability."

Below is my JavaScript file:

        .controller(
        'IncidenteController',
        [
                '$scope',
                '$http',
                '$routeParams',
                'urlinc',
                '$location',
                function($scope, $http, $routeParams, urlinc, $location) {

                    var url = urlinc.getUrlinc();

                    var onError = function(reason) {
                        $scope.error = "Could not retrieve data";
                    };

                    var code = $routeParams.codename;

                    console.log(code);

                    // Various functions for retrieving data from different endpoints

                    $scope.saveIncidente = function(incidente) {
                        // save incident logic
                    };

                    // Other functions and event listeners

                    var that = this;

                    // Object to store opening and closing dates along with their respective status of being open or closed

                    // Function to disable weekend selection

                    // Configuration options for calendar date and time pickers

                    // Function to calculate the difference between two selected dates

                    $scope.$on('$destroy', function() {
                      that.calculateWatch();
                    });

                } ])

EDIT : Managed to make the calculation work as below:

      $scope.calculateUnavailability = function(incident){

                        var closureDate = incident.closure;

                        var openDate = incident.opening;

                        var date1 = Date.parse(closureDate);

                        var date2 = Date.parse(openDate);

                        var diff = date1 - date2;
                         console.log(diff);

                        var days = Math.floor(diff / 1000 / 60 / 60 / 24);
                        diff -= days * 1000 * 60 * 60 * 24

                        var hours = Math.floor(diff / 1000 / 60 / 60);
                        diff -= hours * 1000 * 60 * 60

                        var minutes = Math.floor(diff / 1000 / 60);
                        diff -= minutes * 1000 * 60

                        var unavailability = 'Difference = ' + days + ' day/s ' + hours + ' hour/s ' + minutes + ' minute/s ';

                        console.log(unavailability);

Answer №1

There are two recommended methods to calculate the difference:

1. Manual calculation

The question has been answered previously regarding how to calculate the difference between 2 timestamps using JavaScript.

2. Utilizing Moment.js

moment().format('MMMM Do YYYY, h:mm:ss a'); // December 15th 2015, 11:14:37 am

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

Having a minor problem in attempting to retrieve a random value

Having trouble generating a random number from a function. Can someone help explain? const MyButton = document.querySelector(".Flipper"); MyButton.addEventListener("click", recordLog); function recordLog (){ MyButton.style.backgr ...

What is the best way to store user inputs in a text file using ReactJS?

I have a contact form with three input fields and I would like to save the input values into a text file when users click on a button. How can I achieve this? Can you provide an example? Here is my code: import React, { } from 'react'; import l ...

Creating a Pop-Up on Website Load with HTML, CSS, and Jquery

<script> // utilizing only jquery $(document).ready(function(){ $('#overlay-back').fadeIn(500,function(){ $('#popup').show(); }); $(".close-image").on('click', function() { $('#po ...

Error: The functionality of Object(...) in reactjs is not recognized

After attempting to streamline this react component by moving fillCalendar() out of the component as a method and into its own JS file, I encountered an issue. The original setup involved setting this.state.datesArray in a componentWillMount() lifecycle me ...

Issue with Angular modal: Error displayed instead of opening

I have a PHP page with some PHP functionalities and HTML code. The Angular app is bootstrapped and functioning properly. However, I recently added a modal to open, but it's throwing an error in the console: http://errors.angularjs.org/1.4.8/$compi ...

Make Sequelize default to a future date

Seeking guidance on a specific requirement. I am currently developing an API Express application using Sequelize ORM to interact with MySQL database. In one of the tables, I need to create a column called start_date which will have the default value set ...

Scrolling the inner div with the main scrollbar before navigating through the rest of the page

In my hero div, I have a container div called right-col that contains two inner divs. These inner divs are sticky, creating the effect of cards sliding up when the container div is scrolled. This is the HTML structure: <!DOCTYPE html> <html lang= ...

Error encountered in Firefox: THREE.js throws a TypeError because 'global' is undefined

After attempting to integrate three.js into my code as a standalone script without using webpack, browserify or requirejs, I encountered an issue. My setup involves loading an external Angular app and extending it, but now I need my own version of THREE.js ...

retrieving a URL with the help of $.getJSON and effectively parsing its contents

I seem to be struggling with a coding issue and I can't quite figure out what's wrong. My code fetches a URL that returns JSON, but the function is not returning the expected string: function getit() { var ws_url = 'example.com/test.js&ap ...

An error has been detected by Internet Explorer 8 at line number 373402504

Internet Explorer 8 is throwing an error message that seems to be from a different galaxy ("Expected identifier, string or number") at a line number that makes no sense. Surprisingly, the code functions perfectly on FireFox. Checking the source code, I se ...

Replicate the preceding input data by simply clicking a button

Here is some HTML and jQuery code that I am working with: $(".btn-copy").click(function() { var previousContent = $(this).prev()[0]; previousContent.select(); document.execCommand('copy'); }); <script src="https://cdnjs.cloudflare.com ...

Converting a for loop into a fixed-size array?

I am currently developing a backbone application and have been given some sample code by the provider. The code includes a for loop that generates player names as 'player_1', 'player_2', and so on. However, I would like to manually ente ...

Refreshing CommonJS modules by reloading or reinitializing them

It is well known that CommonJS modules are designed to load only once. Imagine we have a Single Page application with hash-based navigation; when we go back to a page that has already been loaded, the code does not run again because it has already been loa ...

How can I create a thumbnail rectangle and wrap item text with Ionic framework?

Just diving into Ionic and I have a quick query that's not covered in the documentation. Is there a straightforward way to utilize Ionic classes to left-align content currently positioned below an image? The code snippet I'm working with looks ...

Learn how to utilize interpolation within an *ngIf statement in Angular 2 in order to access local template

Consider the following scenario; <div *ngFor="item of items; let i = index;"> <div *ngIf="variable{{i}}">show if variable{{i}} is true</div> </div> Suppose I have variables named "variable0", "variable1",... Is there a way to ac ...

Leveraging JavaScript to determine whether a number is even or exiting by pressing the letter "q"

The main goal is to have the user input a number to check if it is even, or enter 'q' to exit the program. var readlineSync = require('readline-sync'); var i = 0; while (i <= 3) { var num = readlineSync.question ...

There was an error parsing the data from the specified URL (http://localhost:8000/src/client/assets/data.json

Hey there, I'm a newcomer to Angular and I'm having trouble reading a JSON array from a file. Every time I try, it gives me a "failed to parse" error. Can someone please provide some guidance? Here is my folder structure: src --assets ---a ...

Arrange the Elements of Select Options

I am currently facing an issue with organizing the elements in my select list. I have two interconnected lists, one containing a list of "models" which I have successfully sorted using the following function: var sel = $('#model'); var opts_lis ...

Is there a way to show a specific div element only during the initial two occurrences of a jade each loop?

How can I display a specific div only during the first two iterations of a loop in Jade? Is there a way to achieve the following logic in Jade? counter = 0 for each tab in tabs if (counter == 0) div.nav-header NAVIGATION counter++ else if ( ...

Restrict Text Input Field to Accept Only Specific Domain

Hey there! I've set up a text input box for users to link their Tripadvisor page to their profile. I want to make sure that when they paste the URL in, it is checked for the correct format. For example, if someone pastes: or , then allow the link. Ho ...