获取一个字符串时间的x天之前的日期
时间: 2024-01-26 16:05:16 浏览: 27
可以使用Java 8中的LocalDate类和DateTimeFormatter类来实现获取一个字符串时间的x天之前的日期。以下是一个示例代码:
```java
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
public class Main {
public static void main(String[] args) {
// 定义日期格式
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
// 字符串时间转换为LocalDate对象
String strDate = "2021-09-13";
LocalDate date = LocalDate.parse(strDate, formatter);
System.out.println("原日期:" + date);
// 获取x天前的日期
int x = 7;
LocalDate beforeDate = date.minusDays(x);
System.out.println(x + "天前的日期:" + beforeDate);
// 日期格式化
System.out.println("格式化后的日期:" + beforeDate.format(formatter));
}
}
```
输出结果:
```
原日期:2021-09-13
7天前的日期:2021-09-06
格式化后的日期:2021-09-06
```
在上面的示例中,我们首先定义了日期格式,然后将字符串时间转换成LocalDate对象。接着,使用minusDays函数获取x天前的日期,最后使用DateTimeFormatter进行日期格式化。