如何使用moment.js获取日期范围

时间:2016-06-07 07:41:05

标签: javascript jquery html angularjs

这是我的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>

这是我的指示

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

})

我需要使用mument.js获取fromdate和todate之间的范围。任何人都可以建议如何在我的方案中这样做。提前致谢

6 个答案:

答案 0 :(得分:8)

要在两个日期之间获得其余日期,您可以参考此代码 -

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

这是控制台日志: -

  

[“星期二24-05”,“星期三25-05”,“星期四26-05”,“星期五27-05”,“星期六28-05”,“太阳报   29-05“,”星期一30-05“,”星期二31-05“,”星期三01-06“,”星期四02-06“,”星期五   03-06“,”星期六04-06“,”太阳05-06“,”星期一06-06“,”星期二07-06“,”星期三   08-06“,”星期四09-06“,”星期五10-06“,”星期六11-06“,”太阳12-06“,”星期一   13-06“,”星期二14-06“,”星期三15-06“,”星期四16-06“,”星期五17-06“,”星期六   18-06“,”太阳19-06“,”星期一20-06“,”星期二21-06“,”星期三22-06“]

答案 1 :(得分:4)

你可以做这样的事情来改善天数:

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

修改

我为toArray函数添加了一个小例子:

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

答案 2 :(得分:2)

虽然不如提出自己的功能那么有趣,但简单的答案是使用https://github.com/rotaready/moment-range

答案 3 :(得分:2)

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

  return undefined;
};

答案 4 :(得分:0)

如果要在两个日期之间连续获取日期:

  1. 安装MomentJS和MomentRange:npm i moment && npm i moment-range
  2. 某些代码

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*/
});

答案 5 :(得分:0)

我知道这是一个古老的/已回答的问题,但是由于它位于google的顶部,因此如何仅使用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
}

返回两者之间每个“类型”(月/日/小时等)的数组,不包括结束日期

示例:

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