How to get the last week Day (saturday) Date for a particular Date. Means if I give Input as 06-04-2012
(MM-dd-YYYY)
The output should be 06-09-2012
as seen in this calendar.
How to get the last week Day (saturday) Date for a particular Date. Means if I give Input as 06-04-2012
(MM-dd-YYYY)
The output should be 06-09-2012
as seen in this calendar.
Calendar cal = Calendar.getInstance();
int currentDay = cal.get(Calendar.DAY_OF_WEEK);
int leftDays= Calendar.SATURDAY - currentDay;
cal.add(Calendar.DATE, leftDays);
See
LocalDate.parse(
"06-04-2012" ,
DateTimeFormatter.ofPattern( "MM-dd-uuuu" )
).with( TemporalAdjusters.nextOrSame( DayOfWeek.SATURDAY ) )
.format( DateTimeFormatter.ofPattern( "MM-dd-uuuu" ) )
The modern way is with java.time classes.
First parse your input string as a LocalDate
.
DateTimeFormatter f = DateTimeFormatter.ofPattern( "MM-dd-uuuu" );
LocalDate ld = LocalDate.parse( "06-04-2012" , f );
ld.toString(): 2012-06-04
Then get the next Saturday, or use the date itself if it is a Saturday. To specify a Saturday, use the enum DayOfWeek.SATURDAY
. To find that next or same date that is a Saturday, use an implementation of TemporaAdjuster
found in the TemporalAdjusters
(note plural name) class.
LocalDate nextOrSameSaturday =
ld.with( TemporalAdjusters.nextOrSame( DayOfWeek.SATURDAY ) ) ;
To generate a String, I suggest calling toString
to use standard ISO 8601 format.
String output = ld.toString();
2012-06-09
But if you insist, you may use the same formatter as used in parsing.
String output = ld.format( f );
06-09-2012
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date
, Calendar
, & SimpleDateFormat
.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
Where to obtain the java.time classes?
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval
, YearWeek
, YearQuarter
, and more.
Look at either JODA time or (if you cannot add new libraries) the Calendar class.
public Calendar lastDayOfWeek(Calendar calendar){
Calendar cal = (Calendar) calendar.clone();
int day = cal.get(Calendar.DAY_OF_YEAR);
while(cal.get(Calendar.DAY_OF_WEEK) != Calendar.SATURDAY){
cal.set(Calendar.DAY_OF_YEAR, ++day);
}
return cal;
}