HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavascriptMinor

Find the next 8 dates that are Mondays (exclusive of today)

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
theareexclusivedatestodaymondaysnextthatfind

Problem

Any thoughts on improving this method of finding the next 8 Mondays not including today?



var app = angular.module("angularApp", []);
app.controller("appController", function($scope, $filter) {
$scope.mondays = [];

var MILLISECONDS_IN_A_DAY = 1000 60 60 * 24,
now = new Date(),
nowTime = now.getTime(),
mondayOffset = 7 - (now.getDay() - 1);

for (var i = 0; i
body {
font-family: verdana;
font-size: 10pt;
}



{{date | date}}

`

Solution

I think you may have a bug (depends on how the calculation should work). If today is a Sunday, the mondayOffset will be 7 - (0 - 1) == 8, meaning the entire upcoming week will be skipped. In other words, mondayOffset will always be in the range 2-8. I'm guessing that's not what you want.

When dealing with dates, I find it simpler to deal with them as just dates, rather than as millisecond timestamps. Also, with timestamp arithmetic there's always the risk of time zones messing things up for you (for instance when going to/from daylight savings time).

Besides a millisecond number, the Date constructor also accepts separate arguments for year, month, date, hour, etc.. The neat thing is that if you pass a date that doesn't exist, like June 33rd, it'll automatically roll over to July 3rd.

So you can just increment the date argument as needed to produce valid dates in the future:



var app = angular.module("angularApp", []);
app.controller("appController", function($scope, $filter) {
$scope.mondays = [];

var today = new Date(),
year = today.getFullYear(),
month = today.getMonth(),
date = today.getDate(),
offset = 8 - (today.getDay() || 7); // days till next Monday

for(var i = 0 ; i
body {
font-family: verdana;
font-size: 10pt;
}



{{date | date}}





Here the
offset` will be in the range 1-7, so if today's a Sunday, it'll only skip 1 day ahead.

Context

StackExchange Code Review Q#92466, answer score: 4

Revisions (0)

No revisions yet.