Last active
April 17, 2020 15:31
-
-
Save ASHIQUE-KV/12e1e2308c389a32d88c9127a44453c7 to your computer and use it in GitHub Desktop.
Return an array of dates between two given dates. ( TypeScript)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Returns a {key: value} object where the key is a start date and the value is the date + 1 of the type of interval | |
* to the start date. When for weeks or months, it shows just the first date of the week/month. | |
* | |
** For days (start: '2017-12-25', end: '2018-01-02', interval: 'day'): | |
{ '2017-12-25': '2017-12-26', | |
'2017-12-26': '2017-12-27', | |
'2017-12-27': '2017-12-28', | |
'2017-12-28': '2017-12-29', | |
'2017-12-29': '2017-12-30', | |
'2017-12-30': '2017-12-31', | |
'2017-12-31': '2018-01-01', | |
'2018-01-01': '2018-01-02' } | |
* | |
** For weeks (start: '2017-12-18', end: '2018-02-18', interval: 'week'): | |
{ '2017-12-18': '2017-12-25', | |
'2017-12-25': '2018-01-01', | |
'2018-01-01': '2018-01-08', | |
'2018-01-08': '2018-01-15', | |
'2018-01-15': '2018-01-22', | |
'2018-01-22': '2018-01-29', | |
'2018-01-29': '2018-02-05', | |
'2018-02-05': '2018-02-12' } | |
* | |
** For months (start: '2017-12-01', end: '2018-08-31', interval: 'month'): | |
{ '2017-12-01': '2018-01-01', | |
'2018-01-01': '2018-02-01', | |
'2018-02-01': '2018-03-01', | |
'2018-03-01': '2018-04-01', | |
'2018-04-01': '2018-05-01', | |
'2018-05-01': '2018-06-01', | |
'2018-06-01': '2018-07-01', | |
'2018-07-01': '2018-08-01' } | |
* | |
* @param {string} start | |
* @param {string} end | |
* @param {string} interval | |
* @return {{}} | |
*/ | |
import moment, { Moment } from 'moment'; | |
function constructListOfIntervals(start:Moment, end:Moment, interval:string) { | |
var intervals = []; | |
const diffUnitOfTime: string = `${interval}s`; | |
while (moment(end).diff(start, diffUnitOfTime) >= 0) { | |
intervals.push(moment(start)); | |
start = moment(moment(start).add(1, diffUnitOfTime)).format('YYYY-MM-DD'); | |
} | |
return intervals; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment