android – Get day of the week from GregorianCalendar-ThrowExceptions

Exception or error:

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";
    }
How to solve:
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);

###

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

###

tl;dr

myGregCal                  // `GregorianCalendar` is a legacy class, supplanted by the modern `java.time.ZonedDateTime` class.
    .toZonedDateTime()     // Convert to `ZonedDateTime`.
    .getDayOfWeek().       // Extract a `DayOfWeek` enum object, one of seven pre-defined objects, one for each day of the week.
    .getDisplayName(       // Automatically localize, generating a `String` to represent the name of the day of the week.
        TextStyle.SHORT ,  // Specify how long or abbreviated.
        Locale.US          // Locale determines the human language and cultural norms used in localization.
    )                      // Returns a `String` object.

Mon

LocalDate.now( ZoneId.of( "Africa/Tunis" ) )              // Get current date for people in a certain region, without time-of-day and without time zone.
.getDayOfWeek()                                           // Extract a `DayOfWeek` enum object.
.getDisplayName( TextStyle.FULL , Locale.CANADA_FRENCH )  // Generate a string representing that day-of-week, localized using the human language and cultural norms of a particular locale.

lundi

java.time

Convert the troublesome old legacy java.util.GregorianCalendar object to a modern java.time object by calling new methods added to the old class.

ZonedDateTime zdt = myGregCal.toZonedDateTime();

Get the DayOfWeek enum object for that moment in that time zone.

DayOfWeek dow = zdt.getDayOfWeek();

dow.toString(): WEDNESDAY

Pass these DayOfWeek objects around your code rather than passing integers like 1-7 or strings like “MON”. By using the enum objects you make your code more self-documenting, provide type-safety, and ensure a range of valid values.

For presentation to the user, ask the DayOfWeek object to translate the name of the day of the week to a human language defined in a Locale.

String output = 
    dow.getDisplayName( 
        TextStyle.FULL_STANDALONE , 
        Locale.CANADA_FRENCH 
    )
;

mercredi


About java.time

The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.

The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.

To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.

You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.* classes.

Where to obtain the java.time classes?

Leave a Reply

Your email address will not be published. Required fields are marked *