Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add time to date with angular

In my Firebase I have:

Firebase generated date for a created day.

Terms set by the user when the above was generated. 

So for example I have:

1439612582756 // formats to: Aug 14, 2015

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

My code looks like this:

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

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

I have installed moment.js and 'angular-moment.js' to be able to format and play with dates, but I didn't see a way to add time to a date. This is for a for-each so I don't want to have to do any pre-scripting for this. Maybe a custom filter to add the terms to the date?

Obviously, my code above does not function. I just made that to demonstrate what I am wanting.

Any help would be appreciated!

UPDATE

Using this page: http://momentjs.com/docs/#/durations/add/ I came up with this 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();
    }
})

But when I call it, I always end up with just 0?

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

I'm guessing it's because I'm only passing the filter the terms and not the created date. How would you pass two variables? I think I'm getting closer....

UPDATE 2

I dumped the moments crap. This is what I have now:

.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 then in my html:

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

1439746291480 converts to `Aug 16, 2015`

This results in:

8/24/47601
like image 705
moevans Avatar asked Aug 27 '26 00:08

moevans


1 Answers

Using method chaining with Moment.js, you can easily perform these kind of calculations in a single statement. For example:

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

Using Moment.js also will make your life easier in other ways, since it automatically deals with daylight savings, leap years, time zones, etc., making any of your date and time calculations more accurate.

like image 129
Claies Avatar answered Aug 28 '26 14:08

Claies



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!