How do I discover the Quarter of a given Date?

前端 未结 14 1063
小鲜肉
小鲜肉 2020-12-24 05:37

Given a java.util.Date object how do I go about finding what Quarter it\'s in?

Assuming Q1 = Jan Feb Mar, Q2 = Apr, May, Jun, etc.

相关标签:
14条回答
  • 2020-12-24 06:19

    When using Joda time, use Math.ceil() function:

    double quarter = Math.ceil(new Double(jodaDate.getMonthOfYear()) / 3.0);
    
    0 讨论(0)
  • 2020-12-24 06:19

    For Me, I Used this method for string representation:

    int quarter = (Calendar.getInstance().get(Calendar.MONTH) / 3); // 0 to 3
    String[] mQuarterKey = {"qt1", "qt2", "qt3", "qt4"};
    String strQuarter = mQuarterKey[quarter];
    
    0 讨论(0)
  • 2020-12-24 06:20

    Good solutions here, but remember that quarters can be subject to change depending on company/industry too. Sometimes a quarter can be a different 3 months.

    You probably want to extend or encapsulate the calendar class to customize it to your tasks rather than write some utility function that converts it. Your application is probably complex enough in that area that you will find other uses for your new calendar class--I promise you'll be glad you extended or encapsulated it even if it seems silly now.

    0 讨论(0)
  • 2020-12-24 06:21

    You are going to have to write your own code because the term "Quarter" is different for each business. Can't you just do something like:

    Calendar c = /* get from somewhere */
    int month = c.get(Calendar.MONTH);
    
    return (month >= Calendar.JANUARY && month <= Calendar.MARCH)     ? "Q1" :
           (month >= Calendar.APRIL && month <= Calendar.JUNE)        ? "Q2" :
           (month >= Calendar.JULY && month <= Calendar.SEPTEMBER)    ? "Q3" :
                                                                        "Q4";
    
    0 讨论(0)
  • 2020-12-24 06:26

    In Java 8 and later, the java.time classes have a more simple version of it. Use LocalDate and IsoFields

    LocalDate.now().get(IsoFields.QUARTER_OF_YEAR)
    
    0 讨论(0)
  • 2020-12-24 06:26

    If you have

    private static final int[] quarters = {1, 1, 1, 2, 2, 2, 3, 3, 3, 4, 4, 4};
    

    Then current quarter is

    private static final int thisQuarter = quarters[thisMonth];
    

    Where thisMonth is

    private static final int thisMonth = cal.get(Calendar.MONTH);
    
    0 讨论(0)
提交回复
热议问题