4

Problem

I'm using AngularJS and in my view I have 7 days in a row like the pic below. The red, grey, and blue are based on a date (9/1/2013 Sunday). When I click Friday or Monday I want that date to be returned so I can reload the 0/3 with the stats for that date.

I don't need anything fancy for AngularJS I can't figure out the logic to take a base date and then switch the day out for the day that was clicked.


How do I get this to return a date?

  • Current base date: 9/1/2013 - Sunday
  • I click: Thursday
  • I receive: 8/29/2013 - Thursday
  • I click: Sunday
  • I receive: 9/1/2013

What it looks like

enter image description here


I'm currently trying to convert this function from:

JavaScript - get the first day of the week from current date

function getMonday(d) {
  d = new Date(d);
  var day = d.getDay(),
      diff = d.getDate() - day + (day == 0 ? -6:1); // adjust when day is sunday
  return new Date(d.setDate(diff));
}

getMonday(new Date()); // Mon Nov 08 2010

Solved!

I render the dates server side when I render my stats.

Using AngularJS:

Community
  • 1
  • 1
Michael J. Calkins
  • 32,082
  • 15
  • 62
  • 91

2 Answers2

2

Forget about what it looks like, let's focus on what data you have.

If I'm understanding you correctly, you have an associative array of something like:

[{'M',0},{'T',1},{'W',2},{'T',3},{'F',4},{'S',5},{'S',6}]

And you also have a base date

var base = moment('2013-09-01');

And the base is associated with the last value - the 6.

So then what you could do is something like this:

var x = 3; // I clicked on Thursday and got a 3
var target = base.subtract('days', 6-x);  // move back 6-x days

That would work, but wouldn't it be much easier just to precalculate your associative array in the first place?

[{'M','2013-08-26'},
 {'T','2013-08-27'},
 {'W','2013-08-28'},
 {'T','2013-08-29'},
 {'F','2013-08-30'},
 {'S','2013-08-31'},
 {'S','2013-09-01'}]

Then you would already know what value to use when it was clicked.

Matt Johnson-Pint
  • 230,703
  • 74
  • 448
  • 575
1

The problem with moment's day() is that Sunday == 0, not Monday, so you have to jump one week back and use the range 1..7 for Monday..Sunday:

base = '9/1/2013'
console.log(moment(base).day(-7).day(4))
> Thu Aug 29 2013 00:00:00 GMT+0100
console.log(moment(base).day(-7).day(7))
> Sun Sep 01 2013 00:00:00 GMT+0100
georg
  • 211,518
  • 52
  • 313
  • 390
  • It seems to be jumping back 7 days when I click the next month. `scope.date = moment(scope.date).day(-7).day(newDay + 1).format("M/D/YYYY");` [Console screenshot](http://i.imgur.com/aiVrkYl.png) – Michael J. Calkins Sep 01 '13 at 19:33
  • I'm not sure I understand. Could you post your app on jsfiddle? – georg Sep 02 '13 at 09:44