In Moment.js, how do you get the current financial Quarter?

后端 未结 9 1681
深忆病人
深忆病人 2020-12-14 16:07

Is there a simple/built in way of figuring out the current financial quarter?

ex:

  • Jan-Mar: 1st
  • Apr-Jul: 2nd
  • Jul-Sept: 3rd
相关标签:
9条回答
  • 2020-12-14 16:58

    There is nothing built in right now, but there is conversation to add formatting tokens for quarters. https://github.com/timrwood/moment/pull/540

    In the meantime, you could use something like the following.

    Math.floor(moment().month() / 3) + 1;
    

    Or, if you want it on the moment prototype, do this.

    moment.fn.quarter = function () {
        return Math.floor(this.month() / 3) + 1;
    }
    
    0 讨论(0)
  • 2020-12-14 17:01

    START DATE

    moment().quarter(moment().quarter()).startOf('quarter');
    

    Would return the current quarter with the date set to the quarter starting date.

    moment("2019", "YYYY").quarter(4).startOf('quarter');
    

    Would return the starting date of the 4th quarter of the year "2019".

    moment().startOf('quarter');
    

    Would return the starting date of the current quarter of current year.

    END DATE

    moment().quarter(moment().quarter()).endOf('quarter');
    

    Would return the current quarter with the date set to quarter ending date.

    moment("2019", "YYYY").quarter(4).endOf('quarter');
    

    Would return the ending date of the 4th quarter of the year "2019".

    moment().endOf('quarter');
    

    Would return the ending date of the current quarter of current year.

    0 讨论(0)
  • 2020-12-14 17:04

    The simplist way to do this is

    Math.floor(moment.month() / 3)
    

    That will give you the zero based quarter index. ie 0, 1, 2, or 3.

    Then, if you want the quarter's literal number, just add one.

    0 讨论(0)
提交回复
热议问题