Fargho
Fargho

Reputation: 1277

Angular & Javascript: Date is 7 days old and is monday

I have a angular app which is connected to a rest api. To reduce the requests i save all data in the localstorage.

.factory('$localstorage', ['$window', function($window) {
  return {
    set: function(key, value) {
        var object = {value: value, timestamp: new Date().getTime()}
        $window.localStorage[key] = JSON.stringify(valueWithTimestamp);
    },
    setObject: function(key, value) {
        var object = {value: value, timestamp: new Date().getTime()}
        $window.localStorage[key] = JSON.stringify(object);
    },
  }
}]);

There will be new data every monday, so all i want to do is to check if the localstorage is 7 days old and if the current weekday is monday.

Then the data should refresh. Do you have any idea how to solve this simple problem?

Upvotes: 0

Views: 1057

Answers (1)

Fargho
Fargho

Reputation: 1277

Ok, here is my function. Should work now :)

function getNextDayOfWeek(date, dayOfWeek) {
        // Code to check that date and dayOfWeek are valid left as an exercise ;)
        var resultDate = new Date(date.getTime());
        if (date.getDay() === 1 && dayOfWeek === 1) {
          resultDate.setDate(date.getDate() + 7)
        }
        else {
          resultDate.setDate(date.getDate() + (7 + dayOfWeek - date.getDay()) % 7);
        }
        return resultDate;
    }

Upvotes: 1

Related Questions