3

I'm trying to get the first day of the week by date,

This code

  var firstDayOfWeek = new Date(now.setDate(now.getDate() - now.getDay()+1));

returns

Mon Oct 29 2018 17:50:02 GMT+0000 (Greenwich Mean Time)

How do I just get the date in the following format.

YYYY-MM-DD

3 Answers3

2

Considering you don't want to use moment.js.

This is one way of doing that:

var now = new Date()
var firstDayOfWeek = new Date(now.setDate(now.getDate() - now.getDay()+1));

console.log(firstDayOfWeek.toISOString().substring(0,10))
// 2018-10-29

The toISOString() method converts a Date object into a string, using the ISO standard.

The standard is called ISO-8601 and the format is: YYYY-MM-DDTHH:mm:ss.sssZ

omri_saadon
  • 10,193
  • 7
  • 33
  • 58
0

You can use the format and firstDayOfWeek functions of the date-fns library, which doesn't use moment.js, but only raw Date objects.

Here is a snippet achieving what you want:

var firstDayOfWeek = format(startOfWeek(now), 'YYYY-MM-DD');

If you want your week to start on a Monday instead of Sunday by default, you can pass a second argument to startOfWeek like this:

var firstDayOfWeek = format(startOfWeek(now, { weekStartsOn: 1}), 'YYYY-MM-DD');

Lucio
  • 632
  • 5
  • 21
0

You can also do it like this:

function getMonday(d) {
  d = new Date(d);
  const day = d.getDay();
  const diff = d.getDate() - day + (day == 0 ? -6 : 1);
  return new Date(d.setDate(diff));
}

console.log(getMonday(new Date()).toISOString().substring(0, 10));
Willem van der Veen
  • 33,665
  • 16
  • 190
  • 155