java输入日期计算天数_【Java】输入日期,判断这一天是这一年的第几天。

该博客介绍了一个Java程序,用于输入日期并计算它在当年的第几天。程序首先判断输入年份是否为闰年,然后通过累加每个月的天数来确定日期。此外,还提供了检查日期格式、剩余天数等功能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

【任务】

输入日期,判断这一天是这一年的第几天。

【分析】

根据题意,在计算时之前,我们首先应该先判断输入的年份是闰年还是平年。闰年为366天,平年为365天。

确定是闰年还是平年之后,用输入日期加上已经经历过的天数,就是这一年的第几天。

如:以3月5日为例,应该先把前两个月的总天数加起来,然后再加上5天即本年的第几天,特殊情况,闰年且输入月份大于3时需考虑多加一天

01ad95f8ae8ef813ca81a84d0137cb77.png

【实现】

package wyph.task02;

import java.util.Scanner;

public class Task14 {

public static void main(String[] args) {

Scanner sc = new Scanner(System.in);

System.out.println("请输入日期,格式:2018-12-11");

String date = sc.nextLine();

Time time = new Time(date);

System.out.println(time);

}

}

class Time {

String date;

String[] dateArray;

// 年份

int year;

// 月份

int month;

// 日期

int day;

// 总天数

int allDay = 365;

public Time(String date) {

this.date = date;

this.dateArray = date.trim().split("-");

this.year = Integer.parseInt(dateArray[0]);

this.month = Integer.parseInt(dateArray[1]);

this.day = Integer.parseInt(dateArray[2]);

}

// 输入指定日期,返回已经过去了多少天

public int elapsedTime() {

// 计算经历过的天数

int elapsedTime = day;

for (int i = 1; i < this.month; i++) {

elapsedTime = elapsedTime + month(this.year, i);

}

return elapsedTime;

}

// 输入指定日期,返回还剩多少天

public int daysLeft() {

// 计算剩下的天数

int daysLeft = allDay - elapsedTime();

return daysLeft;

}

// 判断输入的日期,是否符合格式要求

public boolean format() {

boolean judge = true;

if ((date.length() != 10) && (date.charAt(4) != '-') && (date.charAt(7) != '-')) {

System.out.println("您输入的日期有误");

judge = false;

}

return judge;

}

// 判断是闰年还是平年

public boolean year(int year) {

boolean judge = false;

if ((year % 4 == 0 && year % 100 != 0) || year % 400 == 0) {

allDay = 366;

judge = true;

}

return judge;

}

// 输入月份返回共有多少天

public int month(int year, int month) {

int day = 0;

switch (month) {

case 1:

case 3:

case 5:

case 7:

case 8:

case 10:

case 12:

day = 31;

break;

case 4:

case 6:

case 9:

case 11:

day = 30;

break;

case 2:

if (year(year)) {

day = 29;

} else {

day = 28;

}

break;

}

return day;

}

// 计算在输入的月份里还剩多少天

public int day(int year, int month, int day) {

int daysLeft = month(year, month) - day;

return daysLeft;

}

public String toString() {

String time = null;

if (month >= 6) {

time = year + "年已过去了" + elapsedTime() + "天,还剩下" + daysLeft() + "天,在剩下的日子里,你要继续加油哦!";

} else {

time = year + "年已过去了" + elapsedTime() + "天,还剩下" + daysLeft() + "天,新的一年才刚刚开始,你要加油哦!";

}

return time;

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值