如何计算一个月的日数? [英] how to calculate number of tuesday in one month?
问题描述
如何计算数量的周二在一个月使用的 JAVA 或机器人 !!
使用 calender.set
我们可以设置特定的一个月,在这之后如何计算周一的人数,在当月星期二等天...
code是:
公共静态无效的主要(字串[] args)
{
台历挂历= Calendar.getInstance();
INT月= calendar.MAY;
INT年= 2012;
INT日期= 1;
calendar.set(年,月,日);
INT MaxDay = calendar.getActualMaximum(calendar.DAY_OF_MONTH);
INT月= 0;
的for(int i = 1; I< MaxDay;我++)
{
calendar.set(Calendar.DAY_OF_MONTH,我);
如果(calendar.get(Calendar.DAY_OF_WEEK)== calendar.MONDAY)
周一++;
}
的System.out.println(日:+ MaxDay);
的System.out.println(星期一+星期一);
}
在这里没有写全code的总体思路是:
日历C = Calendar.getInstance();
c.set(Calendar.MONTH,Calendar.MAY); //也许只是一个例子
c.set(Calendar.YEAR,2012);
INT第= 0;
INT maxDayInMonth = c.getMaximum(Calendar.MONTH);
对于(INT D = 1; D< = maxDayInMonth; d ++){
c.set(Calendar.DAY_OF_MONTH,D);
INT DAYOFWEEK = c.get(Calendar.DAY_OF_WEEK);
如果(Calendar.THURSDAY ==星期几){
日++;
}
}
这code应该算周四的数量。我相信你可以修改它来计算一周的所有天数。
显然,这code是效率不高。它遍历所有的天的月份。您可以通过获取先手的第一天的星期几对其进行优化,在一个月的天数,(我相信)你可以写code,计算一周的每一天的数字,没有遍历整个月。
How to calculate number of Tuesday in one month using JAVA or Android !!
Using calender.set
we can set particular month , after that how to calculate number of Mondays, Tuesdays etc days in that month...
code is :
public static void main(String[] args )
{
Calendar calendar = Calendar.getInstance();
int month = calendar.MAY;
int year = 2012;
int date = 1 ;
calendar.set(year, month, date);
int MaxDay = calendar.getActualMaximum(calendar.DAY_OF_MONTH);
int mon=0;
for(int i = 1 ; i < MaxDay ; i++)
{
calendar.set(Calendar.DAY_OF_MONTH, i);
if (calendar.get(Calendar.DAY_OF_WEEK) == calendar.MONDAY )
mon++;
}
System.out.println("days : " + MaxDay);
System.out.println("MOndays :" + mon);
}
Without writing whole code here is the general idea:
Calendar c = Calendar.getInstance();
c.set(Calendar.MONTH, Calendar.MAY); // may is just an example
c.set(Calendar.YEAR, 2012);
int th = 0;
int maxDayInMonth = c.getMaximum(Calendar.MONTH);
for (int d = 1; d <= maxDayInMonth; d++) {
c.set(Calendar.DAY_OF_MONTH, d);
int dayOfWeek = c.get(Calendar.DAY_OF_WEEK);
if (Calendar.THURSDAY == dayOfWeek) {
th++;
}
}
This code should count number of Thursday. I believe you can modify it to count number of all days of week.
Obviously this code is not efficient. It iterates over all the days in the month. You can optimize it by getting just get day of the week of the first day, the number of days in month and (I believe) you can write code that calculates number of each day of week without iterating over the whole month.
这篇关于如何计算一个月的日数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!