amann
amann

Reputation: 5902

Angular.js – Where to extend JavaScript Date?

I want to extend the basic Date object of JavaScript with more functionality like the following:

Date.prototype.getWeek = function() {
    var date = new Date(this.getTime());
    date.setHours(0, 0, 0, 0);
    // Thursday in current week decides the year.
    date.setDate(date.getDate() + 3 - (date.getDay() + 6) % 7);
    // January 4 is always in week 1.
    var week1 = new Date(date.getFullYear(), 0, 4);
    // Adjust to Thursday in week 1 and count number of weeks from date to week1.
    return 1 + Math.round(((date.getTime() - week1.getTime()) / 86400000 - 3 + (week1.getDay() + 6) % 7) / 7);
};

Currently, I put this logic into a file called objectExtenders.js which is linked in index.html like this:

<script src="scripts/misc/dateExtenders.js"></script>

It doesn't really seem appropriate to put this logic into a service or so, since it modifies the global Date object. Therefore I guess there's no point in injecting such a service into specific controllers, since it will apply to all controllers anyway.

Is there a better way to do this?

Upvotes: 1

Views: 881

Answers (2)

Matsemann
Matsemann

Reputation: 21824

You could instead create a service called DateUtils or so that you inject into your controllers, and that service could have functions that work on dates.

So instead of doing myDate.getWeek() you will call DateUtils.getWeek(myDate).

Upvotes: 3

Ludwig Magnusson
Ludwig Magnusson

Reputation: 14399

You are correct that this kind of modification is global. It affects all Date objects whether they are within angular territory or not. So this question is not in any way related to angular or any other framework. Simply put the code in a JavaScript file and include that file where you want to add this functionality.

Upvotes: 0

Related Questions