用java得到今天0点和上周今天0点时间的格式为"yyyy-MM-dd HH:mm:ss"的字符串
时间: 2023-06-18 08:03:43 浏览: 76
可以使用Java 8的时间API来获取今天0点和上周今天0点的时间,然后将其格式化为字符串。
获取今天0点时间的代码如下:
```java
LocalDateTime now = LocalDateTime.now();
LocalDateTime todayStart = now.with(LocalTime.MIN);
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
String todayStartStr = todayStart.format(formatter);
```
获取上周今天0点时间的代码如下:
```java
LocalDateTime lastWeekTodayStart = now.with(TemporalAdjusters.previous(DayOfWeek.MONDAY)).with(LocalTime.MIN);
String lastWeekTodayStartStr = lastWeekTodayStart.format(formatter);
```
完整代码如下:
```java
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.DayOfWeek;
import java.time.format.DateTimeFormatter;
import java.time.temporal.TemporalAdjusters;
public class Main {
public static void main(String[] args) {
LocalDateTime now = LocalDateTime.now();
LocalDateTime todayStart = now.with(LocalTime.MIN);
LocalDateTime lastWeekTodayStart = now.with(TemporalAdjusters.previous(DayOfWeek.MONDAY)).with(LocalTime.MIN);
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
String todayStartStr = todayStart.format(formatter);
String lastWeekTodayStartStr = lastWeekTodayStart.format(formatter);
System.out.println("今天0点时间:" + todayStartStr);
System.out.println("上周今天0点时间:" + lastWeekTodayStartStr);
}
}
```
输出结果如下:
```
今天0点时间:2022-03-21 00:00:00
上周今天0点时间:2022-03-14 00:00:00
```
阅读全文