Java中两个yyyy-MM-dd HH:mm:ss格式的string类型的时间怎么比较大小
时间: 2024-06-17 09:06:17 浏览: 25
在Java中,我们可以使用SimpleDateFormat类将日期格式化为字符串,然后再将字符串转换为日期对象进行比较。下面是一段代码示例:
```
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String time1 = "2022-01-01 12:00:00";
Date date1 = sdf.parse(time1);
Date date2 = sdf.parse(time2);
if(date1.compareTo(date2) < 0){
System.out.println("time1 < time2");
} else if(date1.compareTo(date2) > 0){
System.out.println("time1 > time2");
} else {
System.out.println("time1 = time2");
}
```
这段代码中,我们定义了一个SimpleDateFormat对象,用于格式化日期字符串。然后我们定义了两个日期字符串time1和time2,并将它们转换为Date对象。最后使用compareTo方法比较两个日期对象的大小。
相关问题
两个yyyy-MM-dd HH:mm:ss格式的string类型的时间怎么比较大小
要比较两个 yyyy-MM-dd HH:mm:ss 格式的字符串时间的大小,需要将它们先转换成时间戳(Unix时间戳),然后再进行比较。时间戳表示自 1970 年 1 月 1 日 00:00:00 以来的秒数,可以用于比较两个时间的先后顺序。
在 C++ 中,可以使用 time.h 头文件中的 mktime() 函数将字符串时间转换成时间戳,然后再进行比较。示例代码如下:
```cpp
#include <iostream>
#include <string>
#include <time.h>
using namespace std;
int main() {
string timeStr1 = "2022-08-01 09:30:00";
string timeStr2 = "2022-08-01 10:30:00";
struct tm tm1 = {0};
strptime(timeStr1.c_str(), "%Y-%m-%d %H:%M:%S", &tm1);
time_t time1 = mktime(&tm1);
struct tm tm2 = {0};
strptime(timeStr2.c_str(), "%Y-%m-%d %H:%M:%S", &tm2);
time_t time2 = mktime(&tm2);
if (time1 < time2) {
cout << timeStr1 << " is earlier than " << timeStr2 << endl;
} else if (time1 > time2) {
cout << timeStr1 << " is later than " << timeStr2 << endl;
} else {
cout << timeStr1 << " and " << timeStr2 << " are the same" << endl;
}
return 0;
}
```
上述代码中,使用 strptime() 函数将字符串时间转换成 tm 结构体类型的时间,然后使用 mktime() 函数将其转换成时间戳,最后比较两个时间戳的大小。需要注意的是,strptime() 函数在 Windows 平台上可能不支持,可以使用 Boost 库中的 date_time 模块来代替。
java string yyyy-mm-dd hh:mm:ss 转 string yyyy-mm-dd
可以使用 Java 中的 SimpleDateFormat 类来将字符串格式化成另一种格式。以下是将 "yyyy-MM-dd HH:mm:ss" 格式的字符串转换为 "yyyy-MM-dd" 格式的代码示例:
```
String dateString = "2022-05-28 13:20:30";
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date date = dateFormat.parse(dateString);
dateFormat.applyPattern("yyyy-MM-dd");
String newDateString = dateFormat.format(date);
System.out.println(newDateString);
```
输出结果为:
```
2022-05-28
```
这样就成功将 "yyyy-MM-dd HH:mm:ss" 格式的字符串转换为 "yyyy-MM-dd" 格式的字符串了。
相关推荐
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)