1.出现:Exception in thread "main" java.lang.ClassCastException: class java.time.format.Parsed cannot be cast to class java.time.LocalDate (java.time.format.Parsed and java.time.LocalDate are in module java.base of loader 'bootstrap')
原因分析:不能直接将TemporalAccessor对象强转成localdate对象 ,应该用localdate.parse转换,
2.出现:Exception in thread "main" java.time.format.DateTimeParseException: Text '2020-11-24' could not be parsed: Unable to obtain LocalDateTime from TemporalAccessor: {},ISO resolved to 2020-11-24 of type java.time.format.Parsed
原因分析:不能将"yyyy-MM-dd"转化为localdatetime的格式,因为缺少时分秒,应该用localdate
代码如下:
/**
* @Auther:ThroneW
* @Date:2020/11/24-11-24-9:36
* @Description:使用localdate打印日历
* @version:1.0
*/
public class TestLocalDatePro {
public static void main(String[] args) {
System.out.print("请输入你想要查看的日期:(提示:请按照例如2012-05-06的格式书写)");
Scanner scanner=new Scanner(System.in);//接受键盘的输入
String input = scanner.next();//接受输入的字符串
//1.定义日期格式
DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd");
//2.创建localdate的对象
LocalDate now = LocalDate.now();
//3.把字符串转变成localdatetime的对象
/*TemporalAccessor parse = df.parse(input);
LocalDate now1=(LocalDate) parse;*/
/*LocalDateTime now1 = LocalDateTime.parse(input, df);*/
LocalDate now1=LocalDate.parse(input,df);
int count=0;
System.out.println("日\t一\t二\t三\t四\t五\t六");
/*DAY_OF_WEEK:星期日:1,星期一:2,星期二:3......*/
//获取nowDay
int nowDay = now1.getDayOfMonth();
//设置时间到当月的第一天,返回相应的星期
/*LocalDateTime now2 = now1.withDayOfMonth(1);*/
LocalDate now2=now1.withDayOfMonth(1);
DayOfWeek dayOfWeek = now2.getDayOfWeek();
int firstDay = dayOfWeek.getValue();
/*System.out.println("firstDay="+firstDay);测试代码,可以忽略*/
firstDay%=7;
for (int j = 1; j <= firstDay; j++) {
System.out.print("\t");
count++;
}
//没有偏移量
/*getDayOfMonth()返回的是这个月的第几天
*lengthOfMonth()返回这个月的长度
* */
for (int i = 1; i <= now1.lengthOfMonth(); i++) {
count++;
if (i==nowDay){
System.out.print(i+"*\t");
}else {
System.out.print(i+"\t");
}
if (count%7==0){
System.out.println();
}
}
}
}
运行结果: