Created
October 13, 2012 19:52
-
-
Save rrguntaka/3885920 to your computer and use it in GitHub Desktop.
Week Start and End Dates in Java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.util.Calendar; | |
import java.util.Date; | |
public class StartEndWeek { | |
private Calendar cal; | |
private int weekStart; | |
public StartEndWeek(Date date, int weekStart) { | |
this.weekStart = weekStart; | |
this.cal = Calendar.getInstance(); | |
this.cal.setTime(date); | |
} | |
private static void startOfDay(Calendar calendar) { | |
calendar.set(Calendar.HOUR, 0); | |
calendar.set(Calendar.MINUTE, 0); | |
calendar.set(Calendar.SECOND, 0); | |
calendar.set(Calendar.AM_PM, 0); | |
} | |
private static void endOfDay(Calendar calendar) { | |
calendar.set(Calendar.HOUR, 11); | |
calendar.set(Calendar.MINUTE, 59); | |
calendar.set(Calendar.SECOND, 59); | |
calendar.set(Calendar.AM_PM, 1); | |
} | |
private int getWeekDay(Calendar calendar) { | |
return calendar.get(Calendar.DAY_OF_WEEK); | |
} | |
private Date getWeekBoundary(boolean isStart) { | |
cal.add(Calendar.DATE, -getWeekDay(cal) + weekStart + (isStart ? 0 : 6)); | |
if (isStart) startOfDay(cal); else endOfDay(cal); | |
return cal.getTime(); | |
} | |
public Date getWeekEnd() { | |
return getWeekBoundary(false); | |
} | |
public Date getWeekStart() { | |
return getWeekBoundary(true); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Inspired from this blog by Guy Bashan