INs INs - 2 years ago 145
Javascript Question

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

I need the fastest way to get the first day of the week. For example today is 11 of november and thursday, i need to convert that date to 8 of november (monday). I need the fastest method for MongoDB map function, any ideas?

Answer Source

Using the getDay method of Date objects, you can know the number of day of the week (being 0=Sunday, 1=Monday, etc).

You can then subtract that number of days plus one, for example:

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
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download