I have a date which is date of a week day(Monday to friday). For example date which I have is 06-07-2016(wednesday). It can be any day from Monday to Friday. And I want to get the previous Saturday (02-07-2016)date of that date.How can I achieve this?
Asked
Active
Viewed 1,654 times
-12
-
1I really dont have an idea how to get this – andro-girl Jul 25 '16 at 12:35
-
3Please read [ask]. – Idos Jul 25 '16 at 12:36
-
4Seriously, a person with 2K reputation; and you expect such a question to fly? – GhostCat Jul 25 '16 at 12:40
-
2Possible duplicate of [Is there a good way to get the date of the coming Wednesday?](http://stackoverflow.com/questions/3463756/is-there-a-good-way-to-get-the-date-of-the-coming-wednesday) – Unknown Jul 25 '16 at 12:41
-
Possible duplicate of [How to get the last Sunday before current date?](http://stackoverflow.com/questions/12783102/how-to-get-the-last-sunday-before-current-date) – Youssef NAIT Jul 25 '16 at 12:41
-
I wrote u a code which will help you. But this is duplicate for sure @seethalakshmi – Aleksandar Đokić Jul 25 '16 at 12:59
3 Answers
3
using java 8 fluent Date/Time classes:
LocalDate inputDate = ...
LocalDate prevSat = inputDate.with(TemporalAdjusters.previous(DayOfWeek.SATURDAY));

Sharon Ben Asher
- 13,849
- 5
- 33
- 47
-
the date which i am setting can be a past date as well not current date – andro-girl Jul 25 '16 at 12:45
-
-
@seethalakshmi, check the documantation for LocalDate to manipulate the date in the past, present or future. https://docs.oracle.com/javase/8/docs/api/java/time/LocalDate.html – Tom Jul 25 '16 at 13:06
-
0
Try this:
Calendar cal=Calendar.getInstance();
cal.add( Calendar.DAY_OF_WEEK, - cal.get(Calendar.DAY_OF_WEEK));
System.out.println(cal.get(Calendar.DATE));

Rahul Tripathi
- 168,305
- 31
- 280
- 331
0
Here. 2 working solutions. I'm first calculating how much days passed till last Saturday and then I'm making new date in which i deduct number which i get from method. That is giving us exact date of last saturday. Second solution is simpler, its using Java 8 features.
import java.time.DayOfWeek;
import java.time.LocalDate;
import java.time.temporal.TemporalAdjuster;
import java.time.temporal.TemporalAdjusters;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;
public class CalendarSat {
public static void main(String[] args) {
Date date = new Date();
date.setDate(date.getDate()-lastSut(date.getDay()));
System.out.println("Custom solution with method: " + date);
LocalDate inputDate = LocalDate.now();
LocalDate prevSat = inputDate.with(TemporalAdjusters.previous(DayOfWeek.SATURDAY));
System.out.println("Java 8 solution: " + prevSat);
}
public static int lastSut(int currentDay) {
int toRet = 0;
int num = 6;
for(int i = 0; i<7;i++) {
if(num==currentDay) {
toRet=i;
}
if(currentDay==0)
currentDay=7;
currentDay--;
}
return toRet;
}
}

Aleksandar Đokić
- 2,118
- 17
- 35