-6

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);

标记的行不会编译。为什么不?我应该如何解决它?

4

1 回答 1

0

您似乎缺少的一点是,当用户输入例如“星期一”时,您需要将此字符串转换为 Java 可以理解为星期几的内容。这是通过解析完成的。幸运的是java.time,使用现代 Java 日期和时间 API 并不难(当您知道如何操作时)。这就是我们dowFormatter在以下代码中使用的 for(dow 表示星期几):

    DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern("yyyy/MM/dd");

    DateTimeFormatter dowFormatter 
            = DateTimeFormatter.ofPattern("EEEE", Locale.getDefault(Locale.Category.FORMAT));
    DayOfWeek dow = DayOfWeek.from(dowFormatter.parse(day));

    WeekFields wf = WeekFields.of(Locale.getDefault(Locale.Category.DISPLAY));

    LocalDate date = LocalDate.of(year, month, 15)
            .with(dow)
            .with(wf.weekOfMonth(), week);
    System.out.println("Result: " + date.format(dateFormatter));

现在,当我输入 2018、7、1 和星期一时,我得到:

结果:2018/07/02

如果您想控制用户应该以哪种语言输入星期几,请将适当的语言环境传递给格式化程序(而不是Locale.getDefault(Locale.Category.FORMAT))。如果你希望它只用英语工作,你可以使用更短的DayOfWeek dow = DayOfWeek.valueOf(day.toUpperCase(Locale.ROOT));,但这有点小技巧。

如果您想控制使用的星期方案,请将适当的语言环境传递给WeekFields.of()或仅指定WeekFields.ISOor WeekFields.SUNDAY_START

我建议你不要使用SimpleDateFormatand Calendar。这些课程早已过时。java.time使用起来要好得多。

链接: Oracle 教程:日期时间解释如何使用java.time.

于 2018-07-12T12:48:47.160 回答