web-dev-qa-db-fra.com

Comment obtenir une plage de dates en utilisant moment.js

Ceci est ma page HTML

<tr ng-show="option == 'Yearly' || option == 'Date'">
            <td>
                <label>From:</label>
            </td>
            <td>
                <input type="text" ng-model="fromdate" id="from" date-picker date-type="from" month-directive />
                {{fromdate}}
            </td>

            <td>
                <label>To:</label>
            </td>
            <td>
                <input id="todate" type="text" ng-model="todate" date-picker date-type="to" month-directive />
                {{todate}}
            </td>

        </tr>

Ceci est ma directive

app.directive('monthDirective', function () {

return {

    restrict:'A',
    link: function (scope, elem) {
        var fromDate, toDate;
        scope.$watch('fromdate', function (newValue, oldValue) {
            fromDate = newValue;
            console.log('fromDate', newValue);
        });
        scope.$watch('todate', function (newValue, oldValue) {
            todate = newValue;
            console.log('todate', newValue);
        });

        var range = moment().range(fromDate, toDate);
        var diff = moment.preciseDiff(fromDate,toDate);
        console.log('Range', range);
        console.log('diff', diff);
    }
}

})

Je dois obtenir la plage entre fromdate et todate en utilisant mument.js. Quelqu'un peut-il suggérer comment faire cela dans mon scénario? Merci d'avance

11
user6269870

Pour obtenir le reste des dates entre deux dates, vous pouvez vous référer à ce code.

$scope.dateArr = []; //Array where rest of the dates will be stored

$scope.prevDate = moment().subtract(15, 'days');//15 days back date from today(This is the from date)

$scope.nextDate = moment().add(15, 'days');//Date after 15 days from today (This is the end date)

//extracting date from objects in MM-DD-YYYY format
$scope.prevDate = moment($scope.prevDate._d).format('MM-DD-YYYY');
$scope.nextDate = moment($scope.nextDate._d).format('MM-DD-YYYY');

//creating JS date objects
var start = new Date($scope.prevDate);
var end = new Date($scope.nextDate);

//Logic for getting rest of the dates between two dates("FromDate" to "EndDate")
while(start < end){
   $scope.dateArr.Push(moment(start).format('ddd DD-MM'));
   var newDate = start.setDate(start.getDate() + 1);
   start = new Date(newDate);  
}

console.log('Dates:- ');
console.log($scope.dateArr);

Voici le journal de la console: -

["Mar 24-05", "Mer 25-05", "Jeu 26-05", "Ven 27-05", "Sam 28-05", "Dim 29-05", "Lun 30- 05 "," Mar 31-05 "," Mer 01-06 "," Jeu 02-06 "," Ven 03-06 "," Sam 04-06 "," Dim 05-06 "," Lun 06-06 "," Mar 07-06 "," Mer 08-06 "," Jeu 09-06 "," Ven 10-06 "," Sam 11-06 "," Dim 12-06 ", "Lun 13-06", "Mar 14-06", "Mer 15-06", "Jeu 16-06", "Ven 17-06", "Sam 18-06", "Dim 19-06 "," Lun 20-06 "," Mar 21-06 "," Mer 22-06 "]

7
sajalsuraj

Vous pouvez faire quelque chose comme ceci pour obtenir la différence en jours: 

var fromDate = moment();
var toDate = moment().add(15, 'days');

var range = moment().range(fromDate, toDate);
var diff = range.diff('days');

var array = range.toArray('days');
$.each(array, function(i, e) {
  $(".container").append("<li>" + moment(e).format("DD MM YYYY") + "</li>");
});

console.log('Range', range);
console.log('diff', diff);

MODIFIER

J'ai ajouté un petit exemple pour la fonction toArray:

https://jsfiddle.net/Tintin37/19n5ykzs/

4
Quentin Roger
const getDaysRange = (date1, date2) => {
  if (date1 && date2) {
    return Math.abs(moment(date2).diff(moment(date1), 'days')) + 1;
  }

  return undefined;
};
2
AuthorProxy

Bien que cela ne soit pas aussi amusant que d’avoir votre propre fonction, la réponse simple est d’utiliser https://github.com/rotaready/moment-range

2
oldo.nicho

Si vous souhaitez obtenir des jours consécutifs entre deux dates:

  1. Installez MomentJS et MomentRange: npm i moment && npm i moment-range
  2. Du code

const 
   Moment = require("moment"),
   MomentRange = require("moment-range"), 
   moment = MomentRange.extendMoment(Moment); /*add plugin to moment instance*/ 

let 
   range = moment().range("2018-02-20", "2018-03-01"), /*can handle leap year*/ 
   array = Array.from(range.by("days")); /*days, hours, years, etc.*/ 

array.map(m => {
     console.log(m.format("YYYY-MM-DD")); /*or any format you like*/
});
0
Adam Bubela