用Java做时间的减法

王朝java/jsp·作者佚名  2008-05-31
宽屏版  字体: |||超大  

活用 GregorianCalendar 类的 getTimeInMillis() 方法。

注重,取到的值是从1970年1月1日00:00:00开始算起所经过的微秒数。一秒是一千微秒。

下面是自己写的一个例程及运行结果:

import Java.util.GregorianCalendar;

class TestClender {

public static void main (String args[]) {

GregorianCalendar ca = new GregorianCalendar();

System.out.println("ca: " + ca);

System.out.println("ca.time: " + ca.getTimeInMillis());

GregorianCalendar ca0 = new GregorianCalendar(2004-1900,11,31,23,59,59);

GregorianCalendar ca1 = new GregorianCalendar(2005-1900,00,01,00,00,02);

long sa = ca1.getTimeInMillis() - ca0.getTimeInMillis();

System.out.println("ca1-ca0: " + sa);

//2004.11.05 added

String old = "20041231235959";

int old_yyyy = Integer.parseInt(old.substring(0,4));

int old_mm = Integer.parseInt(old.substring(4,6));

int old_dd = Integer.parseInt(old.substring(6,8));

int old_hh = Integer.parseInt(old.substring(8,10));

int old_mi = Integer.parseInt(old.substring(10,12));

int old_ss = Integer.parseInt(old.substring(12,14));

String now = "20050101235959";

int now_yyyy = Integer.parseInt(now.substring(0,4));

int now_mm = Integer.parseInt(now.substring(4,6));

int now_dd = Integer.parseInt(now.substring(6,8));

int now_hh = Integer.parseInt(now.substring(8,10));

int now_mi = Integer.parseInt(now.substring(10,12));

int now_ss = Integer.parseInt(now.substring(12,14));

GregorianCalendar gcOld = new GregorianCalendar(

old_yyyy-1900,old_mm-1,old_dd,old_hh,old_mi,old_ss);

GregorianCalendar gcNow = new GregorianCalendar(

now_yyyy-1900,now_mm-1,now_dd,now_hh,now_mi,now_ss);

sa = gcNow.getTimeInMillis() - gcOld.getTimeInMillis();

System.out.println("now-old: " + sa);

}

}

 
 
 
免责声明:本文为网络用户发布,其观点仅代表作者个人观点,与本站无关,本站仅提供信息存储服务。文中陈述内容未经本站证实,其真实性、完整性、及时性本站不作任何保证或承诺,请读者仅作参考,并请自行核实相关内容。
© 2005- 王朝网络 版权所有