Use Java to do time subtraction

Source: Internet
Author: User
Utilize the Gettimeinmillis () method of the GregorianCalendar class.


Note that the value taken is the number of microseconds that have elapsed since 00:00:00 January 1, 1970. One second is 1000 microseconds.





The following is a routine written by yourself and the results of the operation:





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);





}





}











Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.