Java get day of week not exact

I'm trying to figure out which day of the week is the first day of the month, but for some reason it doesn't return me the correct day of the week.

Here is my code below:

CalendarMonth[] months = CalendarUtils.constructMonthViewArray(new GregorianCalendar());


    public static CalendarMonth[] constructMonthViewArray(Calendar cal) {
        CalendarMonth[] months = new CalendarMonth[CALENDAR_GRID_SIZE];


        int year = cal.get(cal.YEAR);
        int month = cal.get(cal.MONTH);;
        // calculate how many days in the month
        int numOfDays = getNumOfDaysInMonth(cal);
        // calculate what day(mon-sunday) is the 1st of the month
        int firstDayOfMonth = getFirstDayOfMonth(cal);



private static int getFirstDayOfMonth(Calendar cal) {
        int firstDay = cal.get(Calendar.DAY_OF_WEEK);

        Log.d(TAG, "");

        // decrement it because our array deals with values 0-6(indexes)
        firstDay--;


        if (firstDay == 0) {
            firstDay = 6;
        } else {
            // decrement again so that the days start from 0.
            firstDay--;
        }
        return firstDay;
    }

      

A string from "int firstDay = cal.get (Calendar.DAY_OF_WEEK);" doesn't give me the correct day of the week and returns 2 to get the 1st of that month (Jan 2011) when the first month was Saturday (7).

Am I missing something? I debugged and checked what month, year and date the cal variable was set in and it did indicate that the date is the date fixed, but when I get the day of the week it doesn't get the value 7.

0


source to share


3 answers


I cannot reproduce the problem you are seeing. As Michael says, there's a lot of code in there that you didn't show us, but Calendar.getDayOfWeek definitely works:

import java.util.*;

public class Test {
    public static void main(String[] args) {
        Calendar calendar = new GregorianCalendar();
        calendar.set(2011, 0, 1); // 0 = January
        System.out.println(calendar.get(Calendar.DAY_OF_WEEK)); // Prints 7
    }
}

      

Perhaps you forgot that months are 0-based java.util.Calendar

?



If you can create a similarly short but complete program that shows the wrong day of the week, please submit it.

The fact that you are decrementing firstDay

twice internally getFirstDayOfMonth

seems somewhat odd, as well as the fact that it doesn't really reflect the method name (as Michael mentioned).

Finally, my constant recommendation for Java date and time handling is: if you can use Joda Time instead java.util.Calendar

, do so. This is a much better API.

+11


source


The getFirstDayOfMonth () code doesn't seem to do what the method name says at all - but to understand what's going on we need to see all the code involved, especially how the calendar is initialized and the getNumOfDaysInMonth () code



One thing to keep in mind: what counts as the first day of the week varies by locale, according to getFirstDayOfWeek()

0


source


java.time

java.util.Calendar / .Date and related classes are confusion as you have learned the hard way.

Those old classes were superseded in Java 8 and later by java.time . The new classes are inspired by the highly successful Joda-Time framework , intended to be its successor, similar in concept but redesigned. Defined by JSR 310 . ThreeTen-Extra is expanding . See Tutorial .

Conversion

If you start with a java.util.Calendar object, convert it to java.time.

An Instant

is a moment on the timeline in UTC .

Instant instant = myJavaUtilCalendarObject.toInstant();

      

Apply timezone to get the date to get the day of the week.

ZoneId zoneId = ZoneId.of( "America/Montreal" );
ZonedDateTime zdt = instant.atZone( zoneId );

      

Note that the time zone is critical in determining the date (and therefore the day of the week). "Today" is not the same place all over the world at the same time. A new day rises earlier, for example, in Paris than in Montreal.

First day of month

Move to the first part of the month by calling withDayOfMonth

.

ZonedDateTime zdtFirstOfMonth = zdt.withDayOfMonth(1);

      

Note that moving the datetime to the first month has problems. Anomalies such as Daylight Saving Time (DST) can have surprising effects. Read the document to understand the behavior.

DayOfWeek

Use a well-named enum throughout the day .DayOfWeek

DayOfWeek dayOfWeek = zdtFirstOfMonth.getDayOfWeek();

      

I suggest passing instances of this enum rather than a magic number , for example 2

, 7

etc. But if you insist, you can extract the whole number.

int dayOfWeekNumber = dayOfWeek.getValue();

      

To get the day of the week name string, let java.time generate a localized string through the getDisplayName

method.

String output = dayOfWeek.getDisplayName( TextStyle.FULL , Locale.CANADA_FRENCH );  // Or Locale.ENGLISH

      

0


source







All Articles