判断两个String类型yyyy-MM-dd HH:mm:ss格式的日期大小
时间: 2024-05-08 14:16:08 浏览: 133
可以将字符串转换成Date类型,然后比较两个Date类型的大小。具体实现如下:
```java
import java.text.SimpleDateFormat;
import java.util.Date;
public class DateCompare {
public static void main(String[] args) {
String dateStr1 = "2021-06-01 12:30:00";
String dateStr2 = "2021-06-01 13:30:00";
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
try {
Date date1 = format.parse(dateStr1);
Date date2 = format.parse(dateStr2);
if (date1.compareTo(date2) < 0) {
System.out.println(dateStr1 + " is before " + dateStr2);
} else if (date1.compareTo(date2) > 0) {
System.out.println(dateStr1 + " is after " + dateStr2);
} else {
System.out.println(dateStr1 + " is equal to " + dateStr2);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
```
输出结果为:
```
2021-06-01 12:30:00 is before 2021-06-01 13:30:00
```
阅读全文