How to get previous/last Saturday for a given date in Java? [duplicate]

127
March 15, 2021, at 11:00 PM
This question already has answers here:
How to get the last Sunday before current date? (7 answers)
Closed 7 hours ago.

For example:- String fromDate="09/18/2020"; I want my actual fromDate to be last Saturday that is "09/12/2020" .

Another example:- String fromDate="09/01/2020"; I want my actual fromDate to be last Saturday that is "08/29/2020" .

Answer 1

TemporalAdjusters.previous

import java.time.DayOfWeek;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.time.temporal.TemporalAdjusters;
import java.util.Locale;
public class Main {
    public static void main(String[] args) {
        String fromDate = "09/18/2020";
        DateTimeFormatter dtf = DateTimeFormatter.ofPattern("M/d/u", Locale.ENGLISH);
        LocalDate date = LocalDate.parse(fromDate, dtf);
        LocalDate result = date.with(TemporalAdjusters.previous(DayOfWeek.SATURDAY));
        // Default LocalDate#toString implementation
        System.out.println(result);
        // Formatted
        System.out.println(result.format(dtf));
    }
}

Output:

2020-09-12
9/12/2020

Learn more about the modern date-time API from Trail: Date Time.

For any reason, if you have to stick to Java 6 or Java 7, you can use ThreeTen-Backport which backports most of the java.time functionality to Java 6 & 7. If you are working for an Android project and your Android API level is still not compliant with Java-8, check Java 8+ APIs available through desugaring and How to use ThreeTenABP in Android Project.

READ ALSO
Why can't I use CSS Variables inside the min() function?

Why can't I use CSS Variables inside the min() function?

The height line throws an errorI thought I could use CSS variables inside the min() function

24
Data is updated on Odoo 11 but not in its DB

Data is updated on Odoo 11 but not in its DB

i have an strange situation on Odoo11 and i discover it because I'm doing an external system to extract the data from Odoo, so every time i update the data in odoo it looks ok on the Odoo System, but when i extract the data using PHP XMLRPC from productproduct...

123
(Covid-19 mask detection using computer vision) Output image not showing

(Covid-19 mask detection using computer vision) Output image not showing

I was reading through this article and copy-pasted the code from here and ran itHowever, the output image window does pop up but no image shows in the window

122
Select every N-hour interval from a table containing long time period

Select every N-hour interval from a table containing long time period

I have a column looks like below, 24-hour displayed from 2019 to 2021 :

108