计算每个月的天数

第一种:

	/**
	 * 计算每个月的天数
	 * 
	 * @param year 年份
	 * @param month 月份
	 * @return days 每个月的天数
	 */
	public static int getDaysOfMonth(int year, int month)
	{
		int days = 0;

		if (month == 1 || month == 3 || month == 5 || month == 7 || month == 8 || month == 10 || month == 12)
		{
			days = 31;
		}
		else if (month == 4 || month == 6 || month == 9 || month == 11)
		{
			days = 30;
		}
		else
		{ // 2月份,闰年29天、平年28天
			if ((year % 4 == 0 && year % 100 != 0) || year % 400 == 0)
			{
				days = 29;
			}
			else
			{
				days = 28;
			}
		}

		return days;
	}


 

第二种:

	/**
	 * 计算每个月的天数
	 * 
	 * @param year 年份
	 * @param month 月份
	 * @return days 每个月的天数
	 */
	public static int getDaysOfMonth2(int year, int month)
	{
		int[] arr = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
		int days = 0;

		if ((year % 4 == 0 && year % 100 != 0) || year % 400 == 0)
		{
			arr[1] = 29; // 闰年2月29天
		}

		try
		{
			days = arr[month - 1];
		}
		catch (Exception e)
		{
			e.getStackTrace();
		}

		return days;
	}


 

  • 2
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 5
    评论
可以使用Java的日期类库进行计算。以下是一个示例代码: ``` import java.time.LocalDate; import java.time.temporal.ChronoUnit; public class DaysBetweenMonths { public static void main(String[] args) { LocalDate date1 = LocalDate.of(2021, 3, 1); LocalDate date2 = LocalDate.of(2021, 6, 30); LocalDate firstDayOfMonth = date1.withDayOfMonth(1); int daysInFirstMonth = ChronoUnit.DAYS.between(date1, firstDayOfMonth.plusMonths(1)); System.out.println("Days in first month: " + daysInFirstMonth); LocalDate lastDayOfMonth = date2.withDayOfMonth(date2.lengthOfMonth()); int daysInLastMonth = ChronoUnit.DAYS.between(lastDayOfMonth, date2.plusDays(1)); System.out.println("Days in last month: " + daysInLastMonth); int fullMonthsBetween = date1.plusMonths(1).until(date2, ChronoUnit.MONTHS); for (int i = 0; i < fullMonthsBetween; i++) { LocalDate currentMonth = date1.plusMonths(i); int daysInCurrentMonth = currentMonth.lengthOfMonth(); System.out.println("Days in month " + (i + 1) + ": " + daysInCurrentMonth); } } } ``` 在这个示例中,我们使用了Java 8中引入的日期类库`java.time`。我们创建了两个`LocalDate`实例,分别表示31日和630日。 我们首先计算了第一个天数。为此,我们使用`withDayOfMonth`方法将日期设置为该的第一天,然后使用`ChronoUnit.DAYS.between`方法计算与原始日期之间的天数。我们将这个天数打印出来。 接下来,我们计算了最后一个天数。为此,我们使用`withDayOfMonth`方法将日期设置为该的最后一天,然后使用`ChronoUnit.DAYS.between`方法计算与原始日期之间的天数。我们将这个天数打印出来。 然后,我们计算了所有完整份的天数。我们使用`plusMonths`方法和`until`方法计算两个日期之间的完整份数。然后,我们使用一个循环来计算每个天数,并将它们打印出来。 这个示例代码的输出将是: ``` Days in first month: 31 Days in last month: 30 Days in month 1: 31 Days in month 2: 30 Days in month 3: 31 Days in month 4: 30 ``` 这表明31日到630日之间的第一个有31天,最后一个有30天,中间的四个完整份分别有31天、30天、31天和30天。
评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值