try{
Date d = format.parse("2009-06-02 12:01:14");
Date ds = new Date();
System.out.println("date:"+new Date().getTime());
System.out.println("days-->"+(ds.getTime()-d.getTime())/(1000*24*60*60));
Date date = new Date();
date.setTime(Long.valueOf("2650867200000"));
System.out.println("setTime:"+date.getTime());
Date date1 = new Date();
date1.setTime(Long.valueOf("1246585845843"));
System.out.println("setTime2:"+date1.getTime());
System.out.println("DIFF:"+((long)(date.getTime()-date1.getTime())/(1000*24*60*60)));
}catch(Exception e)
{}
请问一下怎么算出date与date1之间相差的天数呀?我按照上面的方法算的时候总是不对,但是我直接new一个Date对象然后getTime()的时候算出来是对的,date与date1之间的时间毫秒数现在是从后台得到的,需要计算之间的时间差.请大家帮个忙看看,先谢了.

解决方案 »

  1.   

     //时间比较 
    SimpleDateFormat dateFormat= new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");   
    Date date1= pdi.getId().getUsetime(); 
    Date date2= dateFormat.parse(endtime);   
    long  daytime=(date2.getTime()-date1.getTime())/(24*60*60*1000); 
      

  2.   

    这里的Date d = format.parse("2009-06-02 12:01:14"); 这个format必须这样定义
    SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
      

  3.   

    Date date = new Date(); 
    date.setTime(Long.valueOf("2650867200000")); 
    System.out.println("setTime:"+date.getTime()); 
    Date date1 = new Date(); 
    date1.setTime(Long.valueOf("1246585845843")); 
    System.out.println("DIFF:"+((date.getTime()-date1.getTime())/1000/3600/24));
    我的意思是说怎么计算这两个时间差.也就是这两个值的具体天数.上面这个计算是不准确的结果.
      

  4.   

    就算时间的天数差时,要过滤掉时分秒的影响,所以你上面的方法是有误差的
    可以这么做
              public int daysBetween(Date now, Date returnDate){
        Calendar cNow = Calendar.getInstance();
        Calendar cReturnDate = Calendar.getInstance();
        cNow.setTime(now);
        cReturnDate.setTime(returnDate);
        setTimeToMidnight(cNow);
        setTimeToMidnight(cReturnDate);
        long todayMs = cNow.getTimeInMillis();
        long returnMs = cReturnDate.getTimeInMillis();
        long intervalMs = todayMs - returnMs;
        return millisecondsToDays(intervalMs);
      }   private int millisecondsToDays(long intervalMs) {
        return (int) (intervalMs / (1000 * 86400));
      }   private void setTimeToMidnight(Calendar calendar) {
        calendar.set(Calendar.HOUR_OF_DAY, 0);
        calendar.set(Calendar.MINUTE, 0);
        calendar.set(Calendar.SECOND, 0);
      }代码引用自 http://blog.csdn.net/solomonxu/archive/2007/04/27/1587237.aspx