通过 jdk1.7 实现通过起止时间计算年,保留小数
时间: 2023-09-16 10:07:59 浏览: 52
可以通过以下代码实现:
```java
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class CalculateYear {
public static void main(String[] args) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
String startDateStr = "2010-01-01";
String endDateStr = "2020-12-31";
try {
Date startDate = sdf.parse(startDateStr);
Date endDate = sdf.parse(endDateStr);
long diff = endDate.getTime() - startDate.getTime();
double year = diff / (1000.0 * 60 * 60 * 24 * 365);
DecimalFormat df = new DecimalFormat("#.###");
System.out.println(df.format(year));
} catch (ParseException e) {
e.printStackTrace();
}
}
}
```
首先,我们需要用 SimpleDateFormat 类来解析起止时间的字符串。然后,通过 getTime() 方法获取起止时间的毫秒数差,再将其转换为年数,最后使用 DecimalFormat 格式化输出结果。需要注意的是,在计算年数时需要将毫秒数差除以 (1000.0 * 60 * 60 * 24 * 365),其中 1000 表示 1 秒有 1000 毫秒,60 表示 1 分钟有 60 秒,60 表示 1 小时有 60 分钟,24 表示 1 天有 24 小时,365 表示 1 年有 365 天。