java代码实现两个String日期之间的时间间隔
时间: 2024-05-04 12:15:35 浏览: 76
好的,这是一个关于Java代码实现两个String日期之间的时间间隔的问题。您可以使用Java中的SimpleDateFormat类将字符串日期转换为Date对象,然后使用getTime()方法获取时间戳,最后计算时间差并将其转换为所需的时间单位。以下是一个示例代码:
```
import java.text.SimpleDateFormat;
import java.util.Date;
public class DateInterval {
public static void main(String[] args) {
String date1 = "2021-01-01 00:00:00";
String date2 = "2021-01-02 12:00:00";
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
try {
Date d1 = format.parse(date1);
Date d2 = format.parse(date2);
long diff = d2.getTime() - d1.getTime();
long diffSeconds = diff / 1000 % 60;
long diffMinutes = diff / (60 * 1000) % 60;
long diffHours = diff / (60 * 60 * 1000) % 24;
long diffDays = diff / (24 * 60 * 60 * 1000);
System.out.println("时间间隔为:" + diffDays + "天 " + diffHours + "小时 " + diffMinutes + "分钟 " + diffSeconds + "秒");
} catch (Exception e) {
e.printStackTrace();
}
}
}
```
希望这可以帮助您解决问题!
阅读全文