import java.io.InputStreamReader;
import java.text.ParseException;
import java.util.Calendar;
public class Test9 {
/**
* 9、 编写程序,该程序启动后用户可以按“yyyy-MM-dd”的格式输入一个日期,程序计算这一天是星期几,并且计算出是一年中的第几天。
*
* 分析:将用户输入的日期字符串解析成对应的数字,然后设置给日历对像,再通过日历对像的字段获取需要的信息。
*
* 思路及步骤: (注意:为了代码看起来清析明了,这里对发生的异常不做try{}catch(){}处理)。
* 1.获取键盘录入,得到用户输入的信息;
* 2.封装一个方法,将获取到的信息解析成对应的年、月、日对应的数字;
* 3.创建日历对像;
* 4.将解析完成的年、月、日数字设置给日历对像;
* 5.通过日历对像获取我们所需要的信息;
* 6.将日期信息展示给用户。
*/
public static void main(String[] args) throws IOException, ParseException {
// 提醒用户要输入的日期的格式。
System.out.println("请输入格式为:\"yyyy-MM-dd\"的时期:");
// 获取键盘录入。
BufferedReader bufr = new BufferedReader(new InputStreamReader(System.in));
// 获取到用户输入的日期信息。
String line = bufr.readLine();
// 跟据用户输入的信息,得到相应的日期。
String date = getDate(line);
// 将得到的日期信息展示给用户看(这里只用简单的打印输出展示).
System.out.println(date);
}
// 封装一个方法,将用户输入的字符串解析成相应的日期,并作为字符串返回。
public static String getDate(String field){
String[] ymd = field.split("-");
// 将用户输入字符串的年、月、日解析成对应数字。
int year = Integer.parseInt(ymd[0]);
int month = Integer.parseInt(ymd[1])-1;
int day = Integer.parseInt(ymd[2]);
// 创建日历类对像。
Calendar cale = Calendar.getInstance();
// 将解析好的年、月、日的值设置到日历对像中。
cale.set(year, month, day);
// 跟据日历对像的字段获取对应的年、月、日。
String of_year = cale.get(Calendar.YEAR)+"年";
String of_month = (cale.get(Calendar.MONTH)+1)+"月";
String of_day =cale.get(Calendar.DAY_OF_MONTH)+"日 ";
// 获取星期字段对应的数值。
int week =cale.get(Calendar.DAY_OF_WEEK)-1;
// 跟据日历对像的字段获取年中的天数。
String number = " 年中的第"+cale.get(Calendar.DAY_OF_YEAR)+"天";
// 将解析完成的日期各字段以字符串形式返回。
return of_year+of_month+of_day+getWeekDay(week)+number;
}
// 跟据传入的字段值获取对应的星期数。
public static String getWeekDay(int field){
String[] weeks ={"星期日","星期一","星期二","星期三","星期四","星期五","星期六"};
return weeks[field];
}
}
日历类_应用
最新推荐文章于 2020-09-12 16:30:49 发布