-12

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?

andro-girl
  • 7,989
  • 22
  • 71
  • 94

3 Answers3

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
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