package day01;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
/*
*
* 时间日期转成秒,求差值;
*
*/
public class Demo5 {
public static void main(String[] args) {
// 方式一:
long a = getTimeSecondNum("2024-09-20 12:00:00");
long b = getTimeSecondNum("2024-09-22 12:00:00");
long c = b-a;
System.out.println("c:"+c);
// 方式二:
long c2 = getTimeSecondNum2("2024-09-22 12:00:00","2024-09-20 12:00:00");
System.out.println("c2:"+c2);
}
// 方式一:
private static long getTimeSecondNum(String str){
str = str.replace(" ", "-").replace(":", "-");
long total = 0;
String[] time = str.split("-"); //年月日分割
if(time.length == 6) {
String a = time[1];
long l1 = 0;
long l2 = 0;
if(a.equals("04") || a.equals("06") || a.equals("09") || a.equals("11")) {
l1 = Long.parseLong(time[0]) * 12 * 30 * 24 * 60 * 60 ; // 年转秒
l2 = Long.parseLong(time[1]) * 30 * 24 * 60 * 60; // 月转成秒
}
else if(a.equals("02")) { // 2月统一按照28天计算不区分闰年还平年
l1 = Long.parseLong(time[0]) * 12 * 28 * 24 * 60 * 60 ; // 年转秒
l2 = Long.parseLong(time[1]) * 28 * 24 * 60 * 60; // 月转成秒
}
else {
l1 = Long.parseLong(time[0]) * 12 * 31 * 24 * 60 * 60 ; // 年转秒
l2 = Long.parseLong(time[1]) * 31 * 24 * 60 * 60; // 月转成秒
}
long l3 = Long.parseLong(time[2]) * 1 * 24 * 60 * 60; // 日转秒
long l4 = Long.parseLong(time[3]) * 1 * 1 * 60 * 60; // 时转秒
long l5 = Long.parseLong(time[4]) * 1 * 1 * 1 * 60; // 分转秒
long l6 = Long.parseLong(time[5]); // 秒
total = l1 + l2 + l3 + l4 + l5 + l6;
}
return total;
}
// 方式二:
private static long getTimeSecondNum2(String str1,String str2){
long total = 0;
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
try {
Date date1 = sdf.parse(str1);
Date date2 = sdf.parse(str2);
long seconds1 = date1.getTime() / 1000;
long seconds2 = date2.getTime() / 1000;
total = seconds1 - seconds2;
} catch (ParseException e) {
e.printStackTrace();
}
return total;
}
}
测试:
c:172800
c2:172800