1. 程式人生 > 其它 >獲取兩個時間段相差天數

獲取兩個時間段相差天數


import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class ManyDays {
public static void main(String[] args) throws ParseException {
SimpleDateFormat ss = new SimpleDateFormat("yyyy-MM-dd");//定義新的時間格式,方便後面解析
Date date = new Date();//date資料
String format = ss.format(date)
;//format將現在的日期轉換為string
Date begin = ss.parse("2022-02-20");//simpledateformat中的parse方法解析string,需要此前定義格式
Date end = ss.parse(format);//simpledateformat中的parse方法解析string,需要此前定義格式
Long endTime = end.getTime();//dategettime方法,可以返回毫秒數(從1970年開始到時間點)
Long beginTime = begin.getTime();//date
gettime方法,可以返回毫秒數(從1970年開始到時間點)
Long mathTime = endTime - beginTime;
System.out.println("共計過去:" + mathTime / 1000 / 60 / 60 / 24 + ".");
}
}