oracle 的 trunc 函數能很友善的将日期截斷。現在有個需求,需要用java實作與 oracle 的 trunc 函數 相同的功能。
1.需求:将日期截斷到日
即 将格式為 2018-01-04 03:06:49 日期轉換為 格式為 2018-01-04 的日期
2.實作方法:
用 DateFormat .format 方法擷取隻包含年月日的日期字元串,然後再通過 DateFormat .parse方法将日期字元串轉為日期
DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
//1.擷取開始日期,目前日期 2018-01-04 03:06:49
String startDateStr=df.format(new Date());
Date startDate=df.parse(startDateStr);
System.out.println("開始日期:"+new Date());
System.out.println("startDate:"+startDate);
3.需求拓展:擷取日期相隔天數
方法:
按照之前的思路,我們将兩個日期截斷到日,然後相減即可得到 日期相隔天數
代碼實作:
DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
//1.擷取開始日期,目前日期 2018-01-04 03:06:49
String startDateStr=df.format(new Date());
Date startDate=df.parse(startDateStr);
System.out.println("開始日期:"+new Date());
System.out.println("startDate:"+startDate);
//2.擷取結束日期
String endDateStr="2018-01-06 03:06:49";
Date endDate=df.parse(endDateStr);
System.out.println("結束日期:"+endDate);
//3.求間隔天數
long spanDays=(endDate.getTime()-startDate.getTime() )/ (1000*3600*24);
System.out.println("間隔天數:"+spanDays);