Search code examples
angularmomentjsangular-moment

Moment - Angular generate array of time minus 15min


I have weather satellite image start date 2019_10_08_08_00.jpg .

l am try to generating the following array time slots with a minus of 15 min between each one. for looping images , like the following :

[
"2019_10_08_08_00",
"2019_10_08_07_45",
"2019_10_08_07_30",
"2019_10_08_07_15",
"2019_10_08_07_00",
]

Code :

let startTime = moment('YYYY_M_DD_HH_MM');
let endTime = moment('YYYY_M_DD_HH_MM');

if( endTime.isBefore(startTime) ){
  endTime.add(1, 'day');
}

let timeStops = [];

while(startTime <= endTime){
  timeStops.push(moment(startTime).format('YYYY_M_DD_HH_MM'));
  startTime.subtract(15, 'minutes');
}

console.log(timeStops);

The Problem is l get empty array in console log .

Error code :

moment.js:293 Deprecation warning: value provided is not in a recognized RFC2822 or ISO format. moment construction falls back to js Date(), which is not reliable across all browsers and versions. Non RFC2822/ISO date formats are discouraged and will be removed in an upcoming major release. Please refer to http://momentjs.com/guides/#/warnings/js-date/ for more info.
Arguments: 
[0] _isAMomentObject: true, _isUTC: false, _useUTC: false, _l: undefined, _i: YYYY_M_DD_HH_MM, _f: undefined, _strict: undefined, _locale: [object Object]
Error

Solution

  • You are using the wrong format string. 'MM' is used for month, 'mm' for minutes.

    Also here is a working example

    Edit: Limit loop to 10

        const now = getRoundDate();
    
        const timeStops = [];
    
        for (let i = 0; i < 10; i++) {
          now.subtract(15, 'minutes');
          timeStops.push(now.format('YYYY_M_DD_HH_mm'));
        }
    
        console.log(timeStops);
    
    
        getRoundDate(): moment.Moment {
            const minutes = +moment().format('m');
    
            if (minutes >= 0 && minutes <= 8) return date.minutes(0);
            else if (minutes >= 9 && minutes <= 18) return date.minutes(15);
            else if (minutes >= 19 && minutes <= 38) return date.minutes(30);
            else if (minutes >= 39 && minutes <= 48) return date.minutes(45);
            else if (minutes >= 49) return date.minutes(0).add(1, 'hours')
        }