The method of calculating time difference in Java _java

Source: Internet
Author: User
Tags date now diff

This article illustrates the method of calculating the time difference in Java. Share to everyone for your reference. Specifically as follows:

Let's say it's 2004-03-26 13:31:40.
The past is: 2004-01-02 11:30:24
To get two date difference, the form of difference is: xx days xx hours xx minutes xx seconds

Method One:

DateFormat df = new SimpleDateFormat ("Yyyy-mm-dd HH:mm:ss");
Try
{
  Date D1 = Df.parse ("2004-03-26 13:31:40");
  Date D2 = Df.parse ("2004-01-02 11:30:24");
  Long diff = d1.gettime ()-d2.gettime ();
  Long days = diff/(1000 *);
}
catch (Exception e)
{
}

Method Two:

SimpleDateFormat df = new SimpleDateFormat ("Yyyy-mm-dd HH:mm:ss");
Java.util.Date now = Df.parse ("2004-03-26 13:31:40");
Java.util.Date date=df.parse ("2004-01-02 11:30:24");
Long L=now.gettime ()-date.gettime ();
Long day=l/(24*60*60*1000);
Long hour= (l/(60*60*1000)-day*24);
Long min= ((l/(60*1000))-day*24*60-hour*60);
Long s= (l/1000-day*24*60*60-hour*60*60-min*60);
System.out.println ("" +day+ "Day" +hour+ "hour" +min+ "minute" +s+ "seconds");

Method Three:

SimpleDateFormat dfs = new SimpleDateFormat ("Yyyy-mm-dd HH:mm:ss");
Java.util.Date begin=dfs.parse ("2004-01-02 11:30:24");
Java.util.Date end = Dfs.parse ("2004-03-26 13:31:40");
Long between= (End.gettime ()-begin.gettime ())/1000;
divided by 1000 to convert to a second
long day1=between/(24*3600);
Long hour1=between% (24*3600)/3600;
Long minute1=between%3600/60;
Long second1=between%60/60;
System.out.println ("" +day1+ "Day" +hour1+ "hour" +minute1+ "minute" +second1+ "seconds");

I hope this article will help you with your Java programming.

Related Article

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.