如何获得 Java 中给定日期的 previous/last 星期六?
How to get previous/last Saturday for a given date in Java?
例如:-
字符串 fromDate="09/18/2020";
我希望我的实际开始日期是上周六,即“09/12/2020”。
另一个例子:-
字符串 fromDate="09/01/2020";
我希望我的实际开始日期是上周六,即“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
出于任何原因,如果您必须坚持Java 6 或Java 7,您可以使用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 。
例如:- 字符串 fromDate="09/18/2020"; 我希望我的实际开始日期是上周六,即“09/12/2020”。
另一个例子:- 字符串 fromDate="09/01/2020"; 我希望我的实际开始日期是上周六,即“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
出于任何原因,如果您必须坚持Java 6 或Java 7,您可以使用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