Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get starting date of week(configurable starting day of week)

Tags:

java

I have current date, and a constant which tells from which day the week starts. I want to get the start date of the week based on that constant. If I hardcode the first day of week to Monday(or anything), then it is simple. But the first day of the week keeps changing. So I don't want to change the code, every time the first day is to be changed.

This is what I have tried with java's Calendar:

public static Date getLastWeekdayDate()
{
    Calendar calendar = new GregorianCalendar();
    int dayOfWeek = calendar.get(Calendar.DAY_OF_WEEK);
    int daysToSubtractFromCurrentDate = 0;

    switch (dayOfWeek)
    {
    case Calendar.WEDNESDAY:
        daysToSubtractFromCurrentDate = 4;
        break;

    case Calendar.THURSDAY:
        daysToSubtractFromCurrentDate = 5;
        break;

    case Calendar.FRIDAY:
        daysToSubtractFromCurrentDate = 6;
        break;

    case Calendar.SATURDAY:
        daysToSubtractFromCurrentDate = 0;
        break;

    case Calendar.SUNDAY:
        daysToSubtractFromCurrentDate = 1;
        break;

    case Calendar.MONDAY:
        daysToSubtractFromCurrentDate = 2;
        break;

    case Calendar.TUESDAY:
        daysToSubtractFromCurrentDate = 3;
        break;
    }

    calendar.add(Calendar.DATE, -daysToSubtractFromCurrentDate);
    calendar.set(Calendar.AM_PM, Calendar.AM);
    calendar.set(Calendar.MINUTE, 0);
    calendar.set(Calendar.SECOND, 0);
    calendar.set(Calendar.HOUR, 0);
    calendar.set(Calendar.MILLISECOND, 0);

    return calendar.getTime();
}

I want to get the starting date of the week. The above function returns the first day of the week, and the week start day is hardcoded to Saturday. Whenever the requirement aboout the start day of the week changes, I have to change the code.

like image 352
Syed Aqeel Ashiq Avatar asked Dec 07 '25 00:12

Syed Aqeel Ashiq


1 Answers

From the java calendar API http://docs.oracle.com/javase/6/docs/api/java/util/Calendar.html#getFirstDayOfWeek()

public int getFirstDayOfWeek()
Gets what the first day of the week is; e.g., SUNDAY in the U.S., MONDAY in France.
Returns:
the first day of the week.
See Also:
like image 163
awiebe Avatar answered Dec 08 '25 13:12

awiebe



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!