Win a copy of The Way of the Web Tester: A Beginner's Guide to Automating Tests this week in the Testing forum!

# Difference Between 2 Dates-Contributed by Hari Krishna Kumar @ Chennai

hari krishnakumar
Greenhorn
Posts: 2
How to find difference between 2 dates is a big problem ??

here is the solution

import java.text.SimpleDateFormat;
import java.text.ParseException;
import java.util.Date;
import java.util.Calendar;
import java.util.TimeZone;

public class Diff
{
public static int findMonthsDiff(String sdate1, String sdate2, String fmt)
{
SimpleDateFormat df = new SimpleDateFormat(fmt);
Date date1 = null;
Date date2 = null;
Calendar cal1 = null;
Calendar cal2 = null;

try
{
date1 = df.parse(sdate1);
date2 = df.parse(sdate2);
}
catch (ParseException pe)
{
pe.printStackTrace();
return 2;
}
cal1=Calendar.getInstance();
cal2=Calendar.getInstance();

// different date might have different offset
cal1.setTime(date1);
long ldate1 = date1.getTime() + cal1.get(Calendar.ZONE_OFFSET) + cal1.get(Calendar.DST_OFFSET);
cal2.setTime(date2);
long ldate2 = date2.getTime() + cal2.get(Calendar.ZONE_OFFSET) + cal2.get(Calendar.DST_OFFSET);
// Use integer calculation, truncate the decimals
int hr1 = (int)(ldate1/3600000); //60*60*1000
int hr2 = (int)(ldate2/3600000);
int days1 = (int)hr1/24;
int days2 = (int)hr2/24;
int dateDiff = days2 - days1;
int weekOffset = (cal2.get(Calendar.DAY_OF_WEEK) - cal1.get(Calendar.DAY_OF_WEEK))<0 ? 1 : 0;
int weekDiff = dateDiff/7 + weekOffset;
int yearDiff = cal2.get(Calendar.YEAR) - cal1.get(Calendar.YEAR);
int monthDiff = yearDiff * 12 + cal2.get(Calendar.MONTH) - cal1.get(Calendar.MONTH);
System.out.println();
System.out.println("DateTime 1: " + sdate1);
System.out.println("DateTime 2: " + sdate2);
System.out.println("Date difference : " + dateDiff);
System.out.println("Week difference : " + weekDiff);
System.out.println("Month difference: " + monthDiff);
System.out.println("Year difference : " + yearDiff);
return monthDiff;
}

public static void main(String[] args)
{
String fmt = null;
String sdate1 = null;
String sdate2 = null;
sdate1 = "02/28/2035";
sdate2 = "03/01/2035";
System.out.println("Months Difference Between the dates>> " + findMonthsDiff(sdate1, sdate2, "MM/dd/yyyy"));
}
}

if any problems , queries feel free to mail me
bye

[ October 18, 2005: Message edited by: hari krishnakumar ]

Paul Sturrock
Bartender
Posts: 10336
Your progam will be prone to errors. These lines:

will potentially truncate the result. For example:

So once the dates get far enough apart, the calculation will be wrong.

Ulf Dittmer
Rancher
Posts: 42968
73
If you think that this is a FAQ, you should add a properly working version to the FAQ Wiki. These forums are generally used for questions.