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:
- 모멘트 설치JS 및 모멘트 범위:
npm i moment && npm i moment-range
- 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
'programing' 카테고리의 다른 글
HttpContext에 접근합니다.서로 다른 스레드의 전류 (0) | 2023.10.09 |
---|---|
구조에서 ->와 .의 차이? (0) | 2023.10.09 |
sequelize.js - 수동으로 mysql 패키지를 설치해야 합니다. (0) | 2023.10.09 |
스프링부트-스타터-부모는 폼 파일에서 정확히 무엇을 합니까? (0) | 2023.10.09 |
사용자 수준 스레드는 어떻게 예약/생성되며 커널 수준 스레드는 어떻게 생성됩니까? (0) | 2023.10.09 |