gpt4 book ai didi

java-me - Java ME - 如何获得一个月的天数

转载 作者:行者123 更新时间:2023-12-04 20:13:38 24 4
gpt4 key购买 nike

Java ME java.util.Calendar类没有 getActualMaximum()方法:

...This class has been subset for J2ME based on the JDK 1.3 Calendar class. Many methods and variables have been pruned, and other methods simplified, in an effort to reduce the size of this class.



甚至有可能获得一个月的天数吗?

最佳答案

在 J2ME 中,由于您没有 Calendar.getActualMaximum()可用,您可以尝试以下操作:使用 calculation from this answer ,您可以计算您感兴趣的月份的第一天和下个月的第一天之间的天数。

   private int getDaysInMonth(int month, int year) {
Calendar cal = Calendar.getInstance(); // or pick another time zone if necessary
cal.set(Calendar.MONTH, month);
cal.set(Calendar.DAY_OF_MONTH, 1); // 1st day of month
cal.set(Calendar.YEAR, year);
cal.set(Calendar.HOUR, 0);
cal.set(Calendar.MINUTE, 0);
Date startDate = cal.getTime();

int nextMonth = (month == Calendar.DECEMBER) ? Calendar.JANUARY : month + 1;
cal.set(Calendar.MONTH, nextMonth);
if (month == Calendar.DECEMBER) {
cal.set(Calendar.YEAR, year + 1);
}
Date endDate = cal.getTime();

// get the number of days by measuring the time between the first of this
// month, and the first of next month
return (int)((endDate.getTime() - startDate.getTime()) / (24 * 60 * 60 * 1000));
}

请注意,此方法需要几个月的时间为 Calendar常量,如 Calendar.JANUARY .我认为这些原始整数表示是 0 索引的,所以如果你通过 12对于 12 月,结果可能是错误的。我还没有测试夏令时问题,因此您必须验证这是否足以满足您的应用程序的需求。

像这样使用上面的函数:
  int d = getDaysInMonth(Calendar.DECEMBER, 2012);
d = getDaysInMonth(Calendar.FEBRUARY, 2012);
d = getDaysInMonth(Calendar.FEBRUARY, 2013);

这将产生 d =
31
29
28

(适用于美国时区)。

关于java-me - Java ME - 如何获得一个月的天数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14802719/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com