本文介绍了如何在Java中获取给定日期的上一个/最后一个星期六?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如:-字符串fromDate ="09/18/2020";我希望我的实际fromDate是上周六的"09/12/2020",

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

另一个例子:字符串fromDate ="09/01/2020";我希望我的实际fromDate是上周六的"08/29/2020",

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

推荐答案

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));
    }
}

输出:

2020-09-12
9/12/2020

通过 跟踪:日期,详细了解现代日期时间API.时间 .

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

这篇关于如何在Java中获取给定日期的上一个/最后一个星期六?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-11 22:42