【发布时间】:2018-12-20 14:40:17
【问题描述】:
Java 代码从给定的星期几、月份的星期、月份和年份创建日期作为输入。示例 - 如果输入如下:
天-周一、月-7 月、第 1 周、2018 年、
那么输出应该是-02/07/2018。
下面是使用的代码:
System.out.println("Enter a year,month,week,day:");
int year = Integer.parseInt(obj.nextLine());
int month = Integer.parseInt(obj.nextLine());
int week = Integer.parseInt(obj.nextLine());
String day = obj.nextLine();
String date;
SimpleDateFormat dateFormat = new SimpleDateFormat ("yyyy/MM/dd");
Calendar cal = Calendar.getInstance();
cal.set(Calendar.YEAR, year); // set the year
cal.set(Calendar.MONTH, month-1); // set the month
cal.set(Calendar.WEEK_OF_MONTH, week);
//***error in the below line********
cal.set(Calendar.DAY_OF_WEEK,day);
date=dateFormat.format(cal.getTime());
System.out.println("Result:" +date);
标记的行不会编译。为什么不?我该如何解决?
【问题讨论】:
-
欢迎。到目前为止,您尝试了什么,您在哪里卡住了?如果您不付出任何努力,我们可能无法为您提供帮助。
-
添加了代码,如果我指定星期几,则无法获取日期。谢谢
-
感谢您的代码,它有帮助。您使用的日期和时间类
SimpleDateFormat和Calendar早已过时且设计不佳。我建议你把它们扔在肩膀上,而不是使用java.time, the modern Java date and time API。
标签: java datetime compiler-errors arguments java.util.calendar