public String date_pcon(String beginstr,String endstr)
{
String result="";
Calendar c1=Calendar.getInstance();
Calendar c2=Calendar.getInstance();
Date temp1,temp2;
long l1=0,l2=0,l=0;
int h=0,m=0,s=0;
String time="";
try
{
temp1 = my_time.parse(beginstr);
temp2 = my_time.parse(endstr);
c1.setTime(temp1);
c2.setTime(temp2);
l1 = c1.getTimeInMillis();
l2 = c2.getTimeInMillis();
l=l2-l1;
h=(int)(l/(60*60*1000));
m=(int)((l%(60*60*1000))/(60*1000));
s=(int)(((l%(60*60*1000))%(60*1000))/1000);
result=String.valueOf(h) + ":" + String.valueOf(m) + ":" + String.valueOf(s);
}
catch(Exception e)
{
Write_Err(e);
result="";
}
return result;
}//計算時間差值

解决方案 »

  1.   

    package example;import java.text.SimpleDateFormat;
    import java.text.ParseException;
    import java.util.Date;/**
     *实现如何从字符中time得到时间Date对象只要SimpleDateFormate(String patter)中的每个字符与time的字符对应就行,比如:
    time:   "1981-07-09 10:30:15"      或: "19810709103015"
    patter: "yyyy-MM-dd hh:mm:ss"            "yyyyMMddhhmmss"
    MM must be upper case.
    */
    public class DatetimeFormat{    public static Date strToDate(String strTime, String format){
            Date date = null;;        try{
                SimpleDateFormat tf = new SimpleDateFormat(format);
                date = tf.parse(strTime);            //System.out.println(rtnStr);
            }catch(NullPointerException e){
                System.out.println("the pattern is null.");
            }catch(IllegalArgumentException ex){
                System.out.println("the pattern is invalid.");
            }catch(ParseException e){
                System.out.println("time format error.");
            }        return date;
            
        }
    public static void main(String[] args){
    String s1 = "20041224000000";
    String s2 = "20041121081023";
    Date date1 = strToDate(s1, "yyyyMMddHHmmss");
    Date date2 = strToDate(s2, "yyyyMMddHHmmss"); double length = (date2.getTime()-date1.getTime())/(1000*60*60*24d);
    System.out.println("两个时间相差" + length + "天");
    }
    }
      

  2.   

    Calendar c=Calendar.getInstance();
    c.set(2004,11,24,0,0,0);
    Calendar d=Calendar.getInstance();
    d.set(2004,10,21,8,10,23);
    long m=(c.getTimeInMillis()-d.getTimeInMillis())/(24*3600*1000);
    System.out.println(m);
      

  3.   

    注意c.set(2004,11,24,0,0,0);中的月份从0开始,解析年月日时分秒后,月份减1
      

  4.   

    public int NumDay(Date Date1, Date Date2) {
    int nDay =
    (int) ((Date2.getTime() - Date1.getTime())
    / (24 * 60 * 60 * 1000));
    return nDay;
    }
      

  5.   

    谢谢各位大哥了,我用了另一种方法,用Db2的函数来实现,之前不知道Db2有这样的函数,所以就想自己写。
    db2可以这样实现:select timestampdiff(16,char(timestamp('2004-12-24 10:14:22')-timestamp('2004-12-23 10:14:21'))) from sysibm.sysdummy1