Get day of the week from GregorianCalendar

29,051

Solution 1

TimeZone timezone = TimeZone.getDefault();
Calendar calendar = new GregorianCalendar(timezone);
calendar.set(year, month, day, hour, minute, second);

String monthName=calendar.getDisplayName(Calendar.MONTH, Calendar.SHORT, Locale.getDefault());//Locale.US);
String dayName=calendar.getDisplayName(Calendar.DAY_OF_WEEK, Calendar.SHORT, Locale.getDefault());//Locale.US);

Solution 2

Joda-Time

I use Joda-Time library for all date/time related operations. Joda takes into account you locale and gets results accordingly:

import org.joda.time.DateTime;
DateTime date = new DateTime(year, month, day, 0, 0, 0);

or

DateTime date = DateTime().now();

Day of week (int):

date.getDayOfWeek();

Day of week (short String) using toString() and DateTimeFormat options:

date.toString("EE");
Share:
29,051
MataMix
Author by

MataMix

Updated on July 09, 2022

Comments

  • MataMix
    MataMix almost 2 years

    I have a date and I need to know the day of the week, so I used a GregorianCalendar object but I get back some dates that are incorrect.

    GregorianCalendar calendar = new GregorianCalendar(year, month, day);
    int i = calendar.get(Calendar.DAY_OF_WEEK);
    

    What am I doing wrong?

    Thanks!

    EDIT SOLUTION:

    mont--;
    GregorianCalendar calendar = new GregorianCalendar(year, month, day);
    int i = calendar.get(Calendar.DAY_OF_WEEK);
    
        if(i == 2){
            dayOfTheWeek = "Mon";           
        } else if (i==3){
            dayOfTheWeek = "Tue";
        } else if (i==4){
            dayOfTheWeek = "Wed";
        } else if (i==5){
            dayOfTheWeek = "Thu";
        } else if (i==6){
            dayOfTheWeek = "Fri";
        } else if (i==7){
            dayOfTheWeek = "Sat";
        } else if (i==1){
            dayOfTheWeek = "Sun";
        }
    
  • Lou Morda
    Lou Morda over 9 years
    example: calendar.set(2015, Calendar.JANUARY, 8, 0, 0, 0); would be January 8th, 2015
  • Basil Bourque
    Basil Bourque almost 6 years
    FYI, the Joda-Time project is now in maintenance mode, with the team advising migration to the java.time classes. See Tutorial by Oracle.
  • Basil Bourque
    Basil Bourque almost 6 years
    FYI, the terribly troublesome old date-time classes such as java.util.Date, java.util.Calendar, and java.text.SimpleDateFormat are now legacy, supplanted by the java.time classes built into Java 8 and later. See Tutorial by Oracle.