2

I've a requirement wherein I cannot use JodaDate/Time. I need to use java.util.Date and need a function which returns start Date of the week.

Signature of function:

public java.util.Date getWeekStart(java.util.Date date)

I can assume that the week starts on Sunday. I've done enough research but all solutions are on JodaDate. Can I do this with java.util.Date alone?

Pokechu22
  • 4,984
  • 9
  • 37
  • 62
Srikanth
  • 4,349
  • 3
  • 13
  • 8
  • possible duplicate of [fetch the first date of the week](http://stackoverflow.com/questions/10119782/fetch-the-first-date-of-the-week) and [this](http://stackoverflow.com/q/2109145/642706) and [this](http://stackoverflow.com/q/2937086/642706) and [this](http://stackoverflow.com/q/15503105/642706) and [this](http://stackoverflow.com/q/9307884/642706) and [this](http://stackoverflow.com/q/3023267/642706) and many more. – Basil Bourque Nov 02 '14 at 01:21

2 Answers2

4

Try following code:

public static Date getWeekStart(Date date){
    Calendar c = Calendar.getInstance();
    c.setTime(date);
    int dayOfWeek = c.get(Calendar.DAY_OF_WEEK) - c.getFirstDayOfWeek();
    c.add(Calendar.DAY_OF_MONTH, -dayOfWeek);
    Date firstDate = c.getTime();
        return firstDate;
    }

Input for current date would result in following output: output :

Sun Oct 26 11:46:26 IST 2014

The dig over here is to use Calender for more on it visit this link.

Darshan Lila
  • 5,772
  • 2
  • 24
  • 34
1

You can use calander class for this, it is easy and more flexible. check below function. may it will help you.

public Date getFirstDayOfWeek(Date date){
    Calendar cal=Calendar.getInstance();
    cal.setTime(date);
//  cal.setFirstDayOfWeek(1);  //No need to set , if it is as per local, 1 for sunday and so on. 
    cal.set(Calendar.DAY_OF_WEEK, cal.getFirstDayOfWeek());
    return cal.getTime();
}

It will return first day of the week.

bharatpatel
  • 1,203
  • 11
  • 22