Search code examples
javascriptangularmomentjsionic3angular2-moment

How to get date of last september dynamically with moment.js


I need the date of last September with moment.js - but dynamically.

Current Date

currentDate:string = moment().format('YYYY-MM'); // This will be 2017-10

How to know when the last september was from the current date? I need somethink like this:

lastSteptember = moment(this.currentDate).getDateOfLast('september').format('YYYY-MM');

So the result from now would be:

2017-09

But 3 months ago the result would have been another:

2016-09

How do I can handle this with moment.js?


Solution

  • I found a pretty solution and solved it like this:

    currentYear: number = moment().year();
    lastYear: number = moment().subtract(1, 'years').year();
    nextYear: number = moment().add(1, 'years').year();
    
    if(moment().isSameOrAfter(this.currentYear + '-09-01', 'month')) {
      this.currentServiceYearStartDate = this.currentYear + '-09-01';
      this.currentServiceYearEndDate = this.nextYear + '-08-31';
    } else {
      this.currentServiceYearStartDate = this.lastYear + '-09-01';
      this.currentServiceYearEndDate = this.currentYear + '-08-31';
    }
    
    console.log('Startdate: ' + this.currentServiceYearStartDate);
    console.log('Enddate: ' + this.currentServiceYearEndDate);
    

    https://momentjs.com/docs/#/query/is-same-or-after/