Get the date by day of the week from this date

Problem

I use AngularJS, and in my opinion I have 7 days in a row, as shown below. Red, gray and blue are based on the date (Sunday, 9/1/2013). When I click Friday or Monday, I want to return this date so that I can reload 0/3 with statistics for that date.

I don't need anything interesting for AngularJS. I cannot understand the logic to take the base date and then switch the day to the day that was pressed.


How do I get this to return the date?

  • Current Base Date: 9/1/2013 - Sunday
  • I click: thursday
  • Received: 8/29/2013 - Thursday
  • I click: sunday
  • Received: 9/1/2013

What does it look like

enter image description here


I am currently trying to convert this function from:

JavaScript - get the first day of the week from the 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 provide the server with dates when I do my statistics.

Using AngularJS:

+4
source share
2 answers

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

If I understand 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 connected with the last value - 6.

So what you can 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 

This will work, but is it not much easier to pre-compute your associative array?

 [{'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 already know what value to use when pressed.

+2
source

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

 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 
+1
source

Source: https://habr.com/ru/post/1500042/


All Articles