用Java做時間的減法

來源:互聯網
上載者:User
活用 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);

}

}



聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.