java输入日期计算是这年的第几天:
思路
通过年份区分出是闰年还是平年,平年 2 月 28 天,闰年 2 月 29 天;
1、3、5、7、8、10、12 月份 31 天其余月份均为 30 天;
然后将每个月的天数相加即可,注意如果输入的是 12 月份,则是从 11 月份往前累加到1月份,1月份加的是输入的天数;
实现代码:
import java.util.scanner;/** * created by xpf on 2018/6/22 :) * github:xinpengfei520 * function: */public class calculateutils { /*平年二月28天*/ private static final int days_28 = 28; /*闰年二月29天*/ private static final int days_29 = 29; /*除了31天的月份其他均为30天*/ private static final int days_30 = 30; /*1、3、5、7、8、10、12月份31天*/ private static final int days_31 = 31; public static void main(string[] args) { scanner input = new scanner(system.in); system.out.println("please input year:"); int year = input.nextint(); system.out.println("please input month:"); int month = input.nextint(); system.out.println("please input day:"); int day = input.nextint(); int daysinyear = getdaysinyear(year, month, day); system.out.println("daysinyear:" + daysinyear); } /** * get days in this year * * @param year * @param month * @param day * @return */ public static int getdaysinyear(int year, int month, int day) { int totaldays = 0; switch (month) { // 12 月份加的是11月份的天数,依次类推 case 12: totaldays += days_30; case 11: totaldays += days_31; case 10: totaldays += days_30; case 9: totaldays += days_31; case 8: totaldays += days_31; case 7: totaldays += days_30; case 6: totaldays += days_31; case 5: totaldays += days_30; case 4: totaldays += days_31; case 3: // 判断是否是闰年 if (((year / 4 == 0) && (year / 100 != 0)) || (year / 400 == 0)) { totaldays += days_29; } else { totaldays += days_28; } case 2: totaldays += days_31; case 1: // 如果是1月份就加上输入的天数 totaldays += day; } return totaldays; }}
因为只有2月份的天数和输入的 day 天数是不固定的,其他月份的天数是固定的,而固定的天数是可以通过输入的月份算出来,这样我们就可以这样计算:
2 月份的天数 + 输入的天数 + 计算出来的固定天数
更多java知识请关注java基础教程。
以上就是java中计算指定日期是一年的第几天的方法的详细内容。