源码如下:
String onetime="2023-12-12 18:08:00"
String twotime="2023-12-12 18:00:00"
//格式化时间
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//把字符类型的时间转化为标准时间样式
Date firstDateTimeDate = dateFormat.parse(onetime);
Date secondDateTimeDate = dateFormat.parse(twotime);
//得到时间的总毫秒数
long firstDateMilliSeconds = firstDateTimeDate.getTime();
long secondDateMilliSeconds = secondDateTimeDate.getTime();
//两个日期相减
long subDateMilliSeconds =firstDateMilliSeconds - secondDateMilliSeconds;
//毫秒转化为秒
int totalSeconds = (int) (subDateMilliSeconds/1000);
System.out.println("两次时间相差:"+totalSeconds+"秒");
注意:注意时间格式,一般java获取的是CST时间(CST没测试是否可以直接用,但是String格式没问题!)