Calculate two dates in Java for a few days

Source: Internet
Author: User

1.public class Test {

2.public void DateDiff (String starttime, String endtime, string format) {

3.//generates a Simpledateformate object in the format passed in

4.SimpleDateFormat sd = new SimpleDateFormat (format);

5.long nd = 1000*24*60*60;//number of milliseconds in a day

6.long NH = 1000*60*60;//milliseconds in one hour

7.long nm = 1000*60;//of milliseconds in one minute

8.long ns = 1000;//number of milliseconds in a second

9.long diff;

10.try {

11.//the millisecond time difference for two time

12.diff = Sd.parse (endtime). GetTime ()-Sd.parse (StartTime). GetTime ();

13.long Day = diff/nd;//How many days to calculate the difference

14.long hour = diff%nd/nh;//Calculate how many hours difference

15.long min = diff%nd%nh/nm;//calculation difference How many minutes

16.long sec = diff%nd%nh%nm/ns;//Calculation difference how many seconds

17.//Output Results

18.system.out.println ("Time difference:" +day+ "Day" +hour+ "hour" +min+ "Minute" +sec+ "second. ");

(ParseException e) {

20.e.printstacktrace ();

21.}

22.}

23.

24.

25.public static void Main (string[] args) {

26.new Test (). DateDiff (New SimpleDateFormat ("Yyyy-mm-dd"). Format (new Date ()), "2010-8-23", "yyyy-mm-dd");

27.}

28.}

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.