Summer Developer
Summer Developer

Reputation: 2086

Moment.JS Get The Sunday Before A Given Date

I'm modifying Angular's UI Bootstrap Datepicker to allow for a week selection mode. In order for this to work effectively, I need to set the activeDate to the first Sunday of a given week, so if you select a date, say a Monday like 8/29/2016, it converts your selection into the earlier Sunday, 8/28/16.

This is what the selection function looks like. If interested in the conversion to Sunday logic in the else if block where the alert matches.

$scope.select = function(date) {
    if ($scope.datepickerMode === self.minMode) {
      var dt = ngModelCtrl.$viewValue ? dateParser.fromTimezone(new Date(ngModelCtrl.$viewValue), ngModelOptions.timezone) : new Date(0, 0, 0, 0, 0, 0, 0);
      dt.setFullYear(date.getFullYear(), date.getMonth(), date.getDate());
      dt = dateParser.toTimezone(dt, ngModelOptions.timezone);
      ngModelCtrl.$setViewValue(dt);
      ngModelCtrl.$render();
    } 

    else if($scope.datepickerMode =="week")
      {
        alert("Match!");
        self.activeDate = date.firstSundayofthatweek() //what do I actually put here using Moment.js?
       setMode(self.modes[self.modes.indexOf($scope.datepickerMode) - 1]);
      $scope.$emit('uib:datepicker.mode');
      }

    else {
      self.activeDate = date;
      setMode(self.modes[self.modes.indexOf($scope.datepickerMode) - 1]);
      $scope.$emit('uib:datepicker.mode');
    }

    $scope.$broadcast('uib:datepicker.focus');
  };

I'm using moment.js but can't figure out in their docs how to do it. A vanilla JS answer would also be appreciated. date that is passed to the function is a date object.

Moment docs suggest either:

moment().day(-7);

or

moment().weekday(-7);

but I am passing a date object, not a moment... so do I convert or chain or something? Sorry a bit confused... I also need to return a date object to self.activeDate

Upvotes: 2

Views: 4526

Answers (2)

Abilio Soares
Abilio Soares

Reputation: 21

Moment uses sunday as the first day of the week:

const lastSunday = currentDate => {
  const date = moment(currentDate).startOf('week');
  return date._d;
};

Upvotes: 1

baao
baao

Reputation: 73231

To get the last sunday from a given moment, simply use day() on that moment, together with the days name.

var today = moment("29.08.2016", "DD.MM.YYYY");
var sunday = today.day("Sunday");
console.log(sunday.format("YYYY-MM-DD"));

If you have a Date object, simply parse it as moment

moment(new Date());

Upvotes: 5

Related Questions