Search code examples
javadatetimecompiler-errorsargumentsjava.util.calendar

The method set(int, int) in the type Calendar is not applicable for the arguments (int, String)


Java code to create date from given day of week, week of month, month and year as input. Example- if the iputs are as below:

day-Monday, month-july, week-1, year-2018,

then output should be-02/07/2018.

Below is the code used:

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

The marked line won’t compile. Why not? How should I fix it?


Solution

  • The bit you seem to be missing is that when the user enters for example “Monday”, you need to convert this string into something that Java can understand as a day of week. This is done through parsing. Fortunately using java.time, the modern Java date and time API, it is not so hard (when you know how). This is what we use the dowFormatter for in the following code (dow for day of week):

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

    Now when I enter 2018, 7, 1 and Monday, I get:

    Result: 2018/07/02

    If you want to control in which language the user should enter the day of week, pass the appropriate locale to the formatter (instead of Locale.getDefault(Locale.Category.FORMAT)). If you want it to work in English only, you may use the shorter DayOfWeek dow = DayOfWeek.valueOf(day.toUpperCase(Locale.ROOT));, but it’s a bit of a hack.

    If you want to control the week scheme used, pass the appropriate locale to WeekFields.of() or just specify WeekFields.ISO or WeekFields.SUNDAY_START.

    I recommend that you don’t use SimpleDateFormat and Calendar. Those classes are long outdated. java.time is much nicer to work with.

    Link: Oracle tutorial: Date Time explaining how to use java.time.