当前位置: 技术问答>java相关
给定年和月,如何获得此月的天数??(用jdk自带的类)
来源: 互联网 发布时间:2015-06-01
本文导语: 谢 | Get the number of days in a month public static int daysInMonth(GregorianCalendar c) { int [] daysInMonths = {31,28,31,30,31,30,31,31,30,31,30,31}; daysInMonths[1] += c.isLeapYear(c.get(GregorianCalendar.YEAR)) ? 1 :...
谢
|
Get the number of days in a month
public static int daysInMonth(GregorianCalendar c) {
int [] daysInMonths = {31,28,31,30,31,30,31,31,30,31,30,31};
daysInMonths[1] += c.isLeapYear(c.get(GregorianCalendar.YEAR)) ? 1 : 0;
return daysInMonths[c.get(GregorianCalendar.MONTH)];
}
Actually, the Calendar class provides a method to that very simply. For a given Calendar or GregorianCalendar object : calObject.getActualMaximum(calobject.DAY_OF_MONTH)
In the Java API documentation there is a note saying that The version (getActualMaximum()) of this function on Calendar uses an iterative algorithm to determine the actual maximum value for the field. There is almost always a more efficient way to accomplish this (in most cases, you can simply return getMaximum()). GregorianCalendar overrides this function with a more efficient implementation. So it looks like it's a lot more efficient to call getActualMaximum from a GregorianCalendar object than a Calendar object. (Thanks to P. Harris for the tip) gregCalObject.getActualMaximum(gregCalObject.DAY_OF_MONTH)
public static int daysInMonth(GregorianCalendar c) {
int [] daysInMonths = {31,28,31,30,31,30,31,31,30,31,30,31};
daysInMonths[1] += c.isLeapYear(c.get(GregorianCalendar.YEAR)) ? 1 : 0;
return daysInMonths[c.get(GregorianCalendar.MONTH)];
}
Actually, the Calendar class provides a method to that very simply. For a given Calendar or GregorianCalendar object : calObject.getActualMaximum(calobject.DAY_OF_MONTH)
In the Java API documentation there is a note saying that The version (getActualMaximum()) of this function on Calendar uses an iterative algorithm to determine the actual maximum value for the field. There is almost always a more efficient way to accomplish this (in most cases, you can simply return getMaximum()). GregorianCalendar overrides this function with a more efficient implementation. So it looks like it's a lot more efficient to call getActualMaximum from a GregorianCalendar object than a Calendar object. (Thanks to P. Harris for the tip) gregCalObject.getActualMaximum(gregCalObject.DAY_OF_MONTH)
您可能感兴趣的文章:
本站(WWW.)旨在分享和传播互联网科技相关的资讯和技术,将尽最大努力为读者提供更好的信息聚合和浏览方式。
本站(WWW.)站内文章除注明原创外,均为转载、整理或搜集自网络。欢迎任何形式的转载,转载请注明出处。
本站(WWW.)站内文章除注明原创外,均为转载、整理或搜集自网络。欢迎任何形式的转载,转载请注明出处。