javacalendarjava-timedatejava-calendar

Getting wrong answers from predefined Calendar function in java


I want get a ans of my java program where I want to find out that current day is which day of year, current week is which week of year etc. When I am trying to do this with calendar class methods, it is giving wrong answer.

Below is my code

{
            Calendar c1 = Calendar.getInstance();
            c1.setTime(new Date());
            System.out.println("Today is "+Calendar.DAY_OF_YEAR+" day of year");
            System.out.println("Today is "+Calendar.WEEK_OF_YEAR+" week of year");
            System.out.println("Today is "+Calendar.DAY_OF_WEEK_IN_MONTH+" day of week in month");



    }

Output:-

  Today is 6 day of year
    Today is 3 week of year
    Today is 8 day of week in month

Can anyone please help to find out solution?


Solution

  • Your Calendar variable is c1. But this doesn't reference c1 at all:

    Calendar.DAY_OF_YEAR
    

    So what is it? According to the documentation those are constants which identify the fields to return when querying that object. You don't want to output the constant itself, you want to use it to get the value from your c1 object. Something like this:

    System.out.println("Today is " + c1.get(Calendar.DAY_OF_YEAR) + " day of year");
    

    Repeat for your other fields as well.