cool guy
cool guy

Reputation: 3

Get Day of the month

I understand that java.time package introduced in Java 8 is much simpler to use. However, I am doing a challenge in Java 7 and when I run my code and I am breaking my head as to what the mistake is. I am trying to print Day of the week (in text) on last line. However, it prints null in the last print. If I change the month from 7 to 8, it prints Saturday in the last print statement. Wondering, what I am doing wrong.

Output with month parameter for new GregorianCalendar as 7

Wed Aug 05 00:00:00 AEST 2015

4

null

Output with month parameter for new GregorianCalendar as 8

Sat Sep 05 00:00:00 AEST 2015

7

Saturday

import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.Locale;

public class Test {


    public static void main(String[] args){
        Calendar calendar  = new GregorianCalendar(2015,7,5);
        System.out.println(calendar.getTime().toString());

        System.out.println(calendar.get(Calendar.DAY_OF_WEEK));


        System.out.println(calendar.getDisplayName(calendar.get(Calendar.DAY_OF_WEEK),Calendar.LONG, Locale.getDefault()));


    }
}

Upvotes: 0

Views: 83

Answers (1)

Anonymous
Anonymous

Reputation: 86203

You are correct that you should not use GregorianCalendar in 2019. Not in Java 7 either. java.time, the modern Java date and time API, has been backported. Use ThreeTen Backport. See the links at the bottom.

    LocalDate date = LocalDate.of(2019, Month.AUGUST, 5);
    DayOfWeek dow = date.getDayOfWeek();
    System.out.println(dow.getDisplayName(TextStyle.SHORT, Locale.ENGLISH));

Output is:

Mon

What went wrong in your code?

You had wanted:

    System.out.println(calendar.getDisplayName(Calendar.DAY_OF_WEEK,Calendar.LONG, Locale.getDefault()));

The first argument to getDisplayName is a field code like DAY_OF_WEEK. When instead passing the actual value of that field, you risk giving it an invalid value, in which case the method returns null (which may be confusing — thanks to Kevin Andersson for acknowledging this as Understatement of the year (;->)!).

Field 4 is WEEK_OF_MONTH. The weeks of the month haven’t got names, only numbers, which is why no string representation is applicable for this field. Field 7 is DAY_OF_WEEK, so that you got the expected result in the second case (8 = September) was a mere coincidence.

Links

Upvotes: 1

Related Questions