计算两个时间的相差天数。。

来源:互联网 发布:数学软件那些好 编辑:程序博客网 时间:2024/05/17 01:56
import java.text.ParseException;import java.text.SimpleDateFormat;import java.util.Date;public class Test {public void dateDiff(String startTime, String endTime, String format) {// 按照传入的格式生成一个simpledateformate对象SimpleDateFormat sd = new SimpleDateFormat(format);long nd = 1000 * 24 * 60 * 60;// 一天的毫秒数long nh = 1000 * 60 * 60;// 一小时的毫秒数long nm = 1000 * 60;// 一分钟的毫秒数long ns = 1000;// 一秒钟的毫秒数long diff;try {// 获得两个时间的毫秒时间差异diff = sd.parse(endTime).getTime() - sd.parse(startTime).getTime();long day = diff / nd;// 计算差多少天long hour = diff % nd / nh;// 计算差多少小时long min = diff % nd % nh / nm;// 计算差多少分钟long sec = diff % nd % nh % nm / ns;// 计算差多少秒// 输出结果System.out.println("时间相差:" + day + "天" + hour + "小时" + min + "分钟"+ sec + "秒。");} catch (ParseException e) {e.printStackTrace();}}public static void main(String[] args) {new Test().dateDiff("2012-6-14", new SimpleDateFormat("yyyy-MM-dd").format(new Date()), "yyyy-MM-dd");}}