RelativeRange
Calculate a date range relative to a certain moment.
Contents
Installation
npm
npm i -S moment-relative-range
yarn
yarn add moment-relative-range
Initiation
;; ;
Basic usage
Previous
var range = previous5 'days'; // range.start = 6 days ago// range.end = yesterday// range.length = 5 var previousMonth = rangeprevious1 'months'; // The new range will be relative to the old one// previousMonth.start = start of 1 months ago// previousMonth.end = end of last month// previousMonth.length = the length of the last month in days var previousYear = previousMonthprevious1 'year'; // previousYear.start = start of the year before the previous month// etc.
Next
var range = next2 'month'; // range.start = 1st day of next month// range.end = last day of the month after the next
Current
You can use moment().current(measure)
:
var thisMonth = current'month'; // thisMonth.start = start of the month// thisMonth.end = today// thisMonth.length = the number of days since the start of this month
Combinations
previous1 'year' // Last year current'month' // Last years December previous1 'month' // Last years November next1 'week'; // First week of December last year
Custom
It's also possible to construct a range yourself:
; var range = date: units: 5 measure: 'days'; // The results are the same as above
Options
date
(Date): The date to calculate the range from. requiredmeasure
(String): Things like month, year, day, isoWeek. requiredunits
(Number): The amount of measures. requiredmargin
(Number): A gap between the the date and the end date of the range, in number of days. optionalfixedStart
(Date): A fixed start date. optional
Formatting
#format
current'month'; // 'Jan 1 - 31, 2000'
Default format is ll
. There are two custom formats supported: r
and R
.
r
: today, yesterday, last month, coming week, etc.R
: this day, previous 1 day, previous month, next week, etc.
#locale
You can set the locale of a range by using the #locale
function. This works the same as for a normal moment.
current'month'; // 'Jan 1 - 31, 2000'current'month'; // '1 - 31 jan., 2000'
#toArray
current'month'; // ['YYYY-MM-DD', 'YYYY-MM-DD']
toArray
takes an optional format
parameter. Defaults to YYYY-MM-DD
;
Integrations
moment.range
There is a great package called moment-range, which works great with this package:
; ; const last5DaysRange = previous5 'days'; const momentRange = moment; const last5Days = momentRange; // [day1, day2, day3, day4, day5] const relativeRange = momentRange; relativeRangecurrent'month'; // etc.