Java method for calculating time differences

  • 2020-04-01 03:56:41
  • OfStack

This article illustrates how to calculate time differences in Java. Share with you for your reference. The details are as follows:

So let's say it's 2004-03-26 13:31:40
It used to be: 2004-01-02 11:30:24
To obtain two date differences, the difference is in the form of: 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 * 60 * 60 * 24);
}
catch (Exception e)
{
}

Method 2:


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+" hours "+min+" points "+s+" seconds ");

Method 3:


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;
//We're dividing by 1,000 to convert to seconds
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+" hours "+minute1+" points "+second1+" seconds ");

I hope this article has been helpful to your Java programming.


Related articles: