3

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.

Aqeel Ashiq
  • 1,988
  • 5
  • 24
  • 57
  • Can you please tell us [what you have tried](http://mattgemmell.com/2008/12/08/what-have-you-tried/)? – Uwe Plonus Jul 08 '13 at 07:17
  • @vikingsteve I have edited the question, please have a look – Aqeel Ashiq Jul 08 '13 at 07:25
  • @UwePlonus I have edited the question, please have a look – Aqeel Ashiq Jul 08 '13 at 07:25
  • Probably duplicate : http://stackoverflow.com/questions/1801907/joda-time-first-day-of-week – YMomb Jul 08 '13 at 07:28
  • @awiebe A `GregorianCalendar` starts at the date defined! In Europe the start of the week is Monday in most cases. – Uwe Plonus Jul 08 '13 at 07:29
  • FYI, the troublesome old date-time classes such as [`java.util.Date`](https://docs.oracle.com/javase/8/docs/api/java/util/Date.html), [`java.util.Calendar`](https://docs.oracle.com/javase/8/docs/api/java/util/Calendar.html), and `java.text.SimpleTextFormat` are now [legacy](https://en.wikipedia.org/wiki/Legacy_system), supplanted by the [java.time](https://docs.oracle.com/javase/8/docs/api/java/time/package-summary.html) classes. See [Tutorial by Oracle](https://docs.oracle.com/javase/tutorial/datetime/TOC.html). – Basil Bourque Jul 10 '17 at 23:44

4 Answers4

2

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:
awiebe
  • 3,758
  • 4
  • 22
  • 33
  • Sir how will this help? I want to get date of first day of week. And the the week does not necessarily starts from Sunday or Monday. It can start from any day of week. Have you even read the question? – Aqeel Ashiq Jul 14 '13 at 08:50
  • Yes, I have read the question– but the first day of the week never changes in a given region. What actually happens is that a month may begin on a day which is not the first day of the week. If that's your question then the answer is this, here: http://stackoverflow.com/questions/2109145/how-to-get-first-day-of-a-given-week-number-in-java – awiebe Jul 15 '13 at 21:57
2

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();
}
Aqeel Ashiq
  • 1,988
  • 5
  • 24
  • 57
0

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.
Basil Bourque
  • 303,325
  • 100
  • 852
  • 1,154
0
DateTimeFormatter format = DateTimeFormatter.ofPattern("MM/dd/yyyy");
    LocalDate now = LocalDate.now();
String  startDate = now.with(TemporalAdjusters.previous(DayOfWeek.SUNDAY)).format(format);
kiran..
  • 19
  • 4