分析以下需求,并用代码实现
- 已知日期字符串:“2015-10-20”,将该日期字符串转换为日期对象
- 将(1)中的日期对象转换为日历类的对象
- 根据日期对象获取该日期是星期几,以及这一年的第几天
- 通过键盘录入日期字符串,格式(2015-10-20)
如输入:2015-10-20,输出"2015年-10月-20日 是 星期二,是2015年的第 293 天"
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Scanner;
public class Test {
public static void main(String[] args) throws ParseException {
Scanner sc = new Scanner(System.in);
System.out.println("输入日期字符串(格式 yyyy-MM-dd):");
String strDate = sc.nextLine();
SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd");
Date date = sdf1.parse(strDate);
SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy年-MM月-dd日");
strDate = sdf2.format(date);
Calendar cal = Calendar.getInstance();
cal.setTime(date);
int intDayWeek = cal.get(Calendar.DAY_OF_WEEK);
String dayWeek = "";
switch (intDayWeek) {
case 1:
dayWeek = "星期日";
break;
case 2:
dayWeek = "星期一";
break;
case 3:
dayWeek = "星期二";
break;
case 4:
dayWeek = "星期三";
break;
case 5:
dayWeek = "星期四";
break;
case 6:
dayWeek = "星期五";
break;
case 7:
dayWeek = "星期六";
break;
}
int dayYear = cal.get(Calendar.DAY_OF_YEAR);
System.out.println(strDate + " 是 " + dayWeek + ", " + "是" + cal.get(Calendar.YEAR) + "年的第 " + dayYear + " 天");
}
}