How do I discover the Quarter of a given Date?

前端 未结 14 1062
小鲜肉
小鲜肉 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 05:59

    Since quarters are a localized (Western) concept, specify a Locale rather than using the platform default:

    Calendar cal = Calendar.getInstance(Locale.US);
    /* Consider whether you need to set the calendar's timezone. */
    cal.setTime(date);
    int month = cal.get(Calendar.MONTH); /* 0 through 11 */
    int quarter = (month / 3) + 1;
    

    This will avoid getting the thirteenth month (Calendar.UNDECIMBER) on non-Western calendars, and any skew caused by their shorter months.

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

    I use this method.

     public static Integer getQuarter(Date d){
        Calendar c = Calendar.getInstance();
        c.setTime(d);
        int month = c.get(Calendar.MONTH);
        return (month /3)+1;
    }
    
    0 讨论(0)
  • 2020-12-24 06:06

    JFreeChart has a Quarter class. If you're curious, check out the javadoc. The source is also available from SourceForge if you want to check out the implementation.

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

    You could use

    int quarter = (myDate.getMonth() / 3) + 1;
    

    Be warned, though that getMonth is deprecated:

    As of JDK version 1.1, replaced by Calendar.get(Calendar.MONTH).

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

    Make sure that the thisMonth is at least a float or a double, not an int:

    String quarter = thisMonth/3 <= 1 ? "Q1" : thisMonth/3 <= 2 ? "Q2" : thisMonth/3 <= 3 ? "Q3" : "Q4";
    

    Regards, MS

    0 讨论(0)
  • 2020-12-24 06:16
    int month = Calendar.getInstance().get( Calendar.MONTH ) + 1;
    
    int quarter = month % 3 == 0?  (month / 3): ( month / 3)+1;
    
    0 讨论(0)
提交回复
热议问题