Incorporate duration into date using angular

In my Firebase database, I store the following information:

Timestamp for the day a record was created in Firebase.

Terms entered by the user at the time of creation.

For instance, it may look like this:

1439612582756 // converts to: Aug 14, 2015

15 // Formats to: "Net 15" according to my code 

The code snippet I am currently using is as follows:

<td>{{invoice.settings.created | date}}</td>

<td>{{invoice.settings.created + invoice.settings.terms | date}}</td>

I have added moment.js and 'angular-moment.js' libraries to handle date formatting and manipulation, but I am struggling to add days to a given date without any preprocessing. Is there a way to create a custom filter to achieve this?

As you can see from the sample code above, my current implementation is not working as intended. Any guidance on how to solve this issue would be greatly appreciated!

UPDATE

After referring to the documentation on

http://momentjs.com/docs/#/durations/add/
, I attempted to create a new filter:

.filter('dateTerms', function() {
    return function(created, terms) {
        var a = moment.duration(created, 'd');
        var b = moment.duration(terms, 'd');
        return a.add(b).days();
    }
})

However, when I apply this filter, I only get a result of 0?

<td>{{invoice.settings.created | date}}</td>
<td>{{invoice.settings.terms | dateTerms}}</td> // This line

I suspect this is because I am passing only one variable to the filter. How can I pass two variables to make it work correctly?

UPDATE 2

Deciding to simplify things, I updated my filter as follows:

.filter('dateTerms', function() {
    return function(input, created) {
        var date = new Date(created*1000);
        date.setDate(date.getDate() + input);
        return (date.getMonth()+1)+'/'+ date.getDate() +'/'+date.getFullYear();
    }
})

And in my HTML:

<td>{{invoice.settings.terms | dateTerms:1439746291480}}</td>

1439746291480 converts to `Aug 16, 2015`

This results in:

8/24/47601

Answer №1

By harnessing the power of method chaining in Moment.js, you can effortlessly handle complex calculations with just a single line of code. Take this example:

return moment(new Date(created)).add(terms, 'days').format('MM/DD/YYYY');

Utilizing Moment.js not only simplifies your coding process but also ensures precise date and time calculations by automatically managing daylight savings, leap years, time zones, and more.

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

Checking for an active listening instance of `http.Server` in a Node application

Having an http server and a piece of code that needs to run only when the server is actively listening, I have bound it to the event "listening" as follows : server.on('listening', doSomething) The issue arises when the server is already listen ...

The error message "TypeError: (0, _style.default) is not a function" occurred when using jest along with material

My current configuration looks like this: // .jestrc.json ... "moduleNameMapper": { "style$": "<rootDir>/tests/mock.ts" } // mock.ts export default {} This setup is typically used to exclude assets from jest to pre ...

Having trouble with Angular.js: JSON response not working in $http request

After extensive searching, I'm still unable to find a solution for my first Angular.js app issue: The problem lies with a search form that sends a request to a web server to retrieve a JSON object. Unfortunately, the request fails and triggers the er ...

What steps can be taken to obtain the fully computed HTML rather than the source HTML?

Is there a way to access the final computed HTML of a webpage that heavily relies on javascript to generate its content, rather than just the source HTML? For example, if a page contains script functions that dynamically generate HTML, viewing the page sou ...

Tips for confirming the validity of an email address

Similar Question: How to validate an email address in PHP Could someone please assist me? I am facing issues with validating the email address for the code below. <?php if ($_POST) { $expected = array('name', 'email', &a ...

Is there a way to ensure that an external file function completes before proceeding with the main code execution?

In my project, I have two key JavaScript files: main.js and load.js. Within load.js, there are two essential functions - getData, which makes an AJAX post call, and constHTML, which appends data based on the JSON array returned from the AJAX call. This app ...

After deploying on Vercel, Next.js' getServerSideProps function is returning undefined

I am trying to create a Netflix-inspired website using next.js. I am able to fetch movie data from TMDB using getServerSideProps(). While everything works as expected in development mode, once deployed on Vercel (re-deployed multiple times), the props I re ...

Would it be a security risk to share the Stripe charge ID and connected account ID with clients on the frontend?

I am currently making an ajax call to my backend and I am unsure whether it is secure to reveal the charge id and the connected account id on the client side. Just to clarify, there are no secret keys or sensitive information stored in the browser. Your ...

Connecting Angular Services with Express API for Data Posting

Transitioning my site () from LAMP with Laravel 4 MVC to the MEAN stack has been quite the adventure. The landing page is up and running, with input POSTing to an Angular controller successfully routed. However, I'm facing a challenge in sending the ...

Injecting services into AngularJS controllers helps to provide the necessary dependencies

Greetings! Here is the code snippet for my service: angular.module('lucho1App').factory('ApiExample', ['$http', '$q', function($http, $q) { return { promiseToHaveData: function() { return $ht ...

Managing various swipe interactions using HTML and JavaScript/jQuery

I'm in the process of creating a mobile multiplayer game using HTML5 and Javascript. The jQuery Plugin "touchwipe" is utilized to manage swipe events in various divs like this: $('#play1').touchwipe({ wipeLeft: function(){ if ...

Having various ng-apps within a single parent app

Exploring angularjs for the first time and experimenting with multiple ng-apps on a single page. For example, having app2 inside app1 and app1 within rootApp. controller1 includes an $http service that retrieves id and name values and assigns them to $roo ...

Can the jQuery live function be triggered without the need for an event?

Using the live function in jQuery requires an event to trigger it. More information can be found in the official API documentation. $(".xyz").live('event', function(){ }); I am trying to make the above function run as soon as the dynamicall ...

Can a standalone Angular plugin be developed for seamless integration within different Angular websites?

My affinity for Angular runs deep. That being said, I have a desire to develop an Angular plugin that can be seamlessly integrated into websites using various frameworks. Whether it's Angular or something different, my goal is compatibility across th ...

Is it possible to deinitialize data tables (remove from memory)?

I'm currently utilizing data-tables (with jQuery) on my website. The particular data-table I have implemented seems to be consuming excessive memory in javascript, causing a slowdown in other functionalities. Is there a way for me to de-initialize th ...

What is the best way to calculate the number of days between today's date and the end of the current month using Moment.js?

Here's the current code snippet I am working with: const moment = require('moment') const m = moment const currDay = m().format('D') const dayOfWeek = m().format('dddd') const daysInMonth = m().daysInM ...

I could really use some assistance with the concept of "AJAX" - can anyone help

After spending several months working with AJAX, I have come to understand the typical request lifecycle: Sending parameters to a background page (PHP/ASP/HTML/TXT/XML ... what other options are available?) Performing server-side processing Receiv ...

Securing an AngularJS page with Spring Security is not achievable

I've implemented Spring Security to secure my application using the configuration below in an attempt to display the default Spring login page: spring-security.xml <beans:beans xmlns="http://www.springframework.org/schema/security" xmlns: ...

Oops! We encountered an issue trying to find the "list" view in the views directory

Here are the images I have: This is the code for my app.js file And this is the code for list.ejs located in the views directory Unfortunately, my index.html file is empty. Below is the full error log: Error: Failed to lookup view "list" in the views di ...

Middleware in Express not producing results

Here is the code I am currently using: var express = require('express'); var app = express(); app.use(express.bodyParser()); app.use(express.cookieParser()); var port = Number(process.env.PORT || 5000); app.get('/test/:id', function(r ...