Aqeel Ashiq
Aqeel Ashiq

Reputation: 2185

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

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.

Upvotes: 3

Views: 3307

Answers (4)

kiran..
kiran..

Reputation: 19

DateTimeFormatter format = DateTimeFormatter.ofPattern("MM/dd/yyyy");
    LocalDate now = LocalDate.now();
String  startDate = now.with(TemporalAdjusters.previous(DayOfWeek.SUNDAY)).format(format);

Upvotes: 0

Basil Bourque
Basil Bourque

Reputation: 340118

tl;dr

LocalDate.now( ZoneId.of( "America/Montreal" ) )
         .with( TemporalAdjusters.previousOrSame( DayOfWeek.SUNDAY ) )  // Specify your desired `DayOfWeek` as start-of-week.
         .atStartOfDay( ZoneId.of( "America/Montreal" ) )

See this code run live at IdeOne.com.

zdt: 2017-07-09T00:00-04:00[America/Montreal] | day-of-week: SUNDAY

Avoid legacy classes

You are using the troublesome old date-time classes that are now legacy, supplanted by the java.time classes.

DayOfWeek

Rather than use mere integer numbers to represent day-of-week in your code, use the DayOfWeek enum built into Java. This gains you type-safety, ensures valid values, and makes your code more self-documenting.

DayOfWeek weekStart = DayOfWeek.SUNDAY ;  // Pass whatever `DayOfWeek` object you want.

TemporalAdjuster & LocalDate

The TemporalAdjuster interface enables ways to manipulate a date to get another date. Find some implementations in TemporalAdjusters class (note plural).

ZoneId z = ZoneId.of( "America/Montreal" ) ;
LocalDate today = LocalDate.now( z ) ;
LocalDate start = today.with( TemporalAdjusters.previousOrSame( weekStart ) ) ;  

ZonedDateTime

To get an exact moment, ask the LocalDate for its first moment of the day. That moment depends on a time zone, as the date varies around the globe for any given moment.

ZonedDateTime zdt = start.atStartOfDay( z ) ;

Instant

If you want to view that some moment as in UTC, extract an Instant object.

Instant instant = zdt.toInstant() ;  // Same moment, different wall-clock time.

Upvotes: 0

Aqeel Ashiq
Aqeel Ashiq

Reputation: 2185

I used the following method:

/** 1 = Sunday, 2 = Monday, 3 = Tuesday, 4 = Wednesday, 5 = Thursday,
* 6 = Friday, 7 = Saturday
*/
public static Date getFirstDayOfWeekDate(int firstDay)
{
    // Calculate the date of the first day of the week

    // First get the today's date
    Calendar c = new GregorianCalendar();

    // Now set the day of week to the first day of week
    while (c.get(Calendar.DAY_OF_WEEK) != firstDay)
    {
        c.add(Calendar.DAY_OF_MONTH, -1);
    }

    return c.getTime();
}

Upvotes: 2

awiebe
awiebe

Reputation: 3846

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:

Upvotes: 2

Related Questions