Java中2个DATE类型求天数
//方法一
Date[] d=new Date[2];
d[0]=new Date("...");
d[1]=new Date("...");
Calendar[] cal=new Calendar[2];
for(int i=0;i<cal.length;i++){
cal[i]=Calendar.getInstance();
cal[i].setTime(d[i]);
cal[i].set(Calendar.HOUR_OF_DAY,0);
cal[i].set(Calendar.MINUTE,0);
cal[i].set(Calendar.SECOND,0);
}
long m=cal[0].getTime().getTime();
long n=cal[1].getTime().getTime();
int k=(int)Math.abs((m-n)/1000/3600/24);
//方法二:
public static int getDiffDays(String beginDate, String endDate)throws DefaultException{
java.util.Date td1 = null;
try {
td1 = new SimpleDateFormat("yyyy-MM-dd").parse(beginDate);
} catch (ParseException e1) {
e1.printStackTrace();
}
long lBeginTime = td1.getTime();
java.util.Date td2 = null;
try {
td2 = new SimpleDateFormat("yyyy-MM-dd").parse(endDate);
System.out.println(td2);
} catch (ParseException e) {
e.printStackTrace();
}
long lEndTime = td2.getTime();
int iDay = (int) ((lEndTime - lBeginTime) / 86400000);
return iDay;
//方法三
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
class Test2 {
public static String getDate(){
SimpleDateFormat ft = new SimpleDateFormat("yyyy-MM-dd");
Date dd = new Date();
return ft.format(dd);
}
public static long getQuot(String time1, String time2){
long quot = 0;
SimpleDateFormat ft = new SimpleDateFormat("yyyy-MM-dd");
try {
Date date1 = ft.parse( time1 );
Date date2 = ft.parse( time2 );
quot = date1.getTime() - date2.getTime();
quot = quot / 1000 / 60 / 60 / 24;
} catch (ParseException e) {
e.printStackTrace();
}
return quot;
}
public static void main(String[] args) throws Exception {
String date1 = "2008-8-8";
String date2 = getDate();
long day = getQuot(date1,date2);
System.out.println( "距离"+date1+" 还有 "+day+" 天" );
}
}
//java.text.SimpleDateFormat( "yyyy/MM/dd":String )
//++++ parse(String):Date ->ParseException
//++++ format(Date):String **String格式为new SimpleDateFormat(String)参数格式
//java.util.Date
//++++ getTime():long **返回1970年1月1日之前之后的时刻(毫秒)
//利用java.util.GregorianCalendar计算日期差(毫秒表示)
import java.util.*;
public class ElapsedMillis {
public static void main(String[] args) {
GregorianCalendar gc1 = new GregorianCalendar(1995, 11, 1, 3, 2, 1);
GregorianCalendar gc2 = new GregorianCalendar(1995, 11, 1, 3, 2, 2);
// the above two dates are one second apart
Date d1 = gc1.getTime();
Date d2 = gc2.getTime();
long l1 = d1.getTime();
long l2 = d2.getTime();
long difference = l2 - l1;
System.out.println("Elapsed milliseconds: " + difference);
}
}