programing

How to get date range using moment.js

instargram 2023. 10. 9. 21:21
반응형

How to get date range using moment.js

This is my html page

<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>

This is my 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);
    }
}

})

I need to get the range between fromdate and todate using mument.js. Can anyone suggest how to do this in my scenario. Thanks in advance

이것이 오래된/답변된 질문이라는 것을 알고 있지만, 구글에서 가장 높은 위치에 있기 때문에, 이것은 단지 그것만으로 날짜 범위를 달성하는 방법입니다.moment(그리고 없는 경우)moment-range):

import moment from 'moment'

/**
 * @param {date|moment} start The start date
 * @param {date|moment} end The end date
 * @param {string} type The range type. eg: 'days', 'hours' etc
 */
function getRange(startDate, endDate, type) {
  let fromDate = moment(startDate)
  let toDate = moment(endDate)
  let diff = toDate.diff(fromDate, type)
  let range = []
  for (let i = 0; i < diff; i++) {
    range.push(moment(startDate).add(i, type))
  }
  return range
}

Returns an array of every "type" (month/day/hour etc) between the two, exclusive of the end date

Example:

let range = getRange('2019-01-01', '2019-01-05', 'days')
// moment dates -> [ '2019-01-01', '2019-01-02', '2019-01-03', '2019-01-04' ]

To get rest of the dates between two dates, you can refer this 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);

This is the console log:-

["Tue 24-05", "Wed 25-05", "Thu 26-05", "Fri 27-05", "Sat 28-05", "Sun 29-05", "Mon 30-05", "Tue 31-05", "Wed 01-06", "Thu 02-06", "Fri 03-06", "Sat 04-06", "Sun 05-06", "Mon 06-06", "Tue 07-06", "Wed 08-06", "Thu 09-06", "Fri 10-06", "Sat 11-06", "Sun 12-06", "Mon 13-06", "Tue 14-06", "Wed 15-06", "Thu 16-06", "Fri 17-06", "Sat 18-06", "Sun 19-06", "Mon 20-06", "Tue 21-06", "Wed 22-06"]

You can do something like this to get the difference in days:

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);

EDIT

제가 예를 하나 더 추가했습니다.toArray함수:

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

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

  return undefined;
};

If you want to get consecutive days between two dates:

  1. 모멘트 설치JS 및 모멘트 범위:npm i moment && npm i moment-range
  2. Some 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*/
});

To get range of dates in the array, you can try my not perfect and not optimized function below.

Case description:

There are two dates:

1) 01.01.2023

2) 31.01.2023

Expected result:

const resultArr = [01.01.2023, 02.01.2023, 03.01.2023, 04.01.2023, 05.01.2023, ..., 31.01.2023]

Solution with using moment.js library:

/**
 * @name getRangeDatesBetweenTwoDates
 * @param _minDate {Moment}
 * @param _maxDate {Moment}
 * @param _format {string}
 * @param _currentDate {Moment}
 * @returns {*[]|*}
 */

export const getRangeDatesBetweenTwoDates = (
  _minDate,
  _maxDate,
  _format = dateFormat,
  _currentDate,
) => {
  const rangeDates = [];

  const getDatesRecursively = (
    minDate,
    maxDate,
    format = dateFormat,
    currentDate,
  ) => {
    const minDateStart = moment(
      minDate.startOf('day').format(serverDateFormat),
      serverDateFormat,
    );
    const maxDateStart = moment(
      maxDate.startOf('day').format(serverDateFormat),
      serverDateFormat,
    );

    if (
      minDateStart.isAfter(maxDateStart) ||
      !minDate ||
      !maxDate ||
      !currentDate
    )
      return;

    if (currentDate.isSame(maxDateStart)) {
      rangeDates.push(currentDate.format(dateFormat));

      return rangeDates;
    }

    rangeDates.push(currentDate.format(dateFormat));

    const _nextDay = moment(currentDate)
      .add(1, 'days')
      .format(serverDateFormat);

    return getDatesRecursively(
      minDateStart,
      maxDateStart,
      format,
      moment(_nextDay, serverDateFormat),
    );
  };

  return getDatesRecursively(_minDate, _maxDate, _format, _currentDate);
};

dateRanges is your resultArr

const dateRanges = getRangeDatesBetweenTwoDates(
  moment(01.01.2023, 'DD.MM.YYYY'),
  moment(31.01.2023, 'DD.MM.YYYY'),
  'DD.MM.YYYY',
  moment(01.01.2023, 'DD.MM.YYYY'),
);

Recommended to optimize and simplify this function by removing extra moment wrappers

ReferenceURL : https://stackoverflow.com/questions/37673322/how-to-get-date-range-using-moment-js

반응형