DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
try
{
Date d1 = df.parse("2004-03-26 13:31:40");
Date d2 = df.parse("2004-01-02 11:30:24");
long diff = d1.getTime() - d2.getTime();//这样得到的差值是微秒级别
long days = diff / (1000 * 60 * 60 * 24);
long hours = (diff-days*(1000 * 60 * 60 * 24))/(1000* 60 * 60);
long minutes = (diff-days*(1000 * 60 * 60 * 24)-hours*(1000* 60 * 60))/(1000* 60);
System.out.println(""+days+"天"+hours+"小时"+minutes+"分");
}
catch (Exception e)
{
}
d1 d2就是2个日期,打印出来的是天 小时 和分 你可以自己转换一下变成天
比如2012-01-02到2015-09-31之间的天数
先算出两个年之间相差的天数:
for(start=2012; start<2015;start++){
days += 365;
if(start==闰年)
days+=1;
算出2012那个日期(2012-01-02)是当年(2012)第几天:day1
算出2015那个日期(2015-09-31)是当年(2015)第几天:day2
算出实际相差天数: day = days+day2-day1;
代码如下:
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
public class Time {
public static void main(String args[]) {
String myString = "2015-06-10 00:00:00";
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.CHINA);
Date now1 = new Date();
String now=sdf.format(now1);
Date date = null;
try {
now1 = sdf.parse(now);
date = sdf.parse(myString);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
long l=now1.getTime()-date.getTime();
long day=l/(24*60*60*1000);
long hour=day*24;
long mon=day/30;
long year=mon/12;
System.out.println("相差"+hour+"小时");
System.out.println("相差"+day+"天");
System.out.println("相差"+mon+"月");
System.out.println("相差"+year+"年");
}
}
满意请采纳