概述
I am trying to get the quarter in the year using calender class in Java. I am getting current date as below and use WEEK_OF_YEAR variable to get the week as below but below output is not making much sense to me as this week is not 3rd week in this year.
Calendar cal = Calendar.getInstance();
System.out.println(dateFormat.format(cal.getTime()));
System.out.println("week of year: "+cal.WEEK_OF_YEAR);
output: 2014/02/17
week of year: 3
What i wanted to do is, i want to have below quarter (Currently Quarter1 is running and next Quarter is Quarter2) as result and use this on my application.
Quarter1 is from Week 1 to Week 12.
Quarter2 is from Week 13 to Week 24.
Quarter3 is from Week 25 to Week 37.
Quarter4 is from Week 38 to the end of the year.
Please help me with this and let me know how do i find out Quarters as mentioned above.
解决方案
Calendar.WEEK_OF_YEAR is a constant. You wanted cal.get(Calendar.WEEK_OF_YEAR).
However, you should note that "week of year" is not as simple as you might expect, as a concept. For example, it can be 53 on January 1st, which belongs to the previous week-year in some years. Are you happy for the first quarter of a year to start later than January 1st?
(Unless you really need to use a week-year/week-of-week-year/day-of-week representation for business purposes, year/month/day is much easier to get your head around.)
If you do need to translate the week-of-year into a quarter after reading those caveats, you can just use:
public static int getQuarter(Calendar calendar) {
int weekOfYear = calendar.get(Calendar.WEEK_OF_YEAR);
return weekOfYear < 13 ? 1
: weekOfYear < 25 ? 2
: weekOfYear < 38 ? 3
: 4;
}
最后
以上就是繁荣毛巾为你收集整理的quarter java,根据Java中的Week查找Quarter的全部内容,希望文章能够帮你解决quarter java,根据Java中的Week查找Quarter所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
发表评论 取消回复