BeginnersBook

  • Home
  • Java
    • Java OOPs
    • Java Collections
    • Java Examples
  • C
    • C Examples
  • C++
    • C++ Examples
  • DBMS
  • Computer Network
  • Python
    • Python Examples
  • More…
    • jQuery
    • Kotlin
    • WordPress
    • SEO
    • JSON
    • JSP
    • JSTL
    • Servlet
    • MongoDB
    • XML
    • Perl

Java date difference

Last Updated: September 11, 2022 by Chaitanya Singh | Filed Under: java

Most of the Java application involves date format data and related computations. Calculating difference between two date values is one of the important and frequently performed operation.

Following code shows how we can obtain difference between two date values. We will check if the date difference between provided two dates is more than 30 months.

1. getDateDiff method : This method calculates difference between two dates

2. StrTokens : This method parses given date value and obtain the year, month and day part of given date. These year, month and day parts will be used by getDateDiff method while computing the difference.

Method : getDateDiff

[code language=”java”]
public static String getDateDiff(String strStartDate, String strEndDate)
{
int iStartDay, iEndDay, iStartMonth, iEndMonth, iStartYear, iEndYear = 0;
int iStartDate, iEndDate, iDateDiff = 0;
if (strStartDate.trim().equals("") || strEndDate.trim().equals(""))
{
return ("Success");
}
else
{
String strDelim = "/";
StrTokens StartDate = new StrTokens (strStartDate, strDelim);
StrTokens EndDate = new StrTokens (strEndDate, strDelim);
iStartYear = StartDate.getIYear();
iEndYear = EndDate.getIYear();
iStartMonth = StartDate.getIMonth();
iEndMonth = EndDate.getIMonth();
iStartDay = StartDate.getIDate();
iEndDay = EndDate.getIDate();
iStartYear = iStartYear * 12;
iEndYear = iEndYear * 12;
iStartDate = iStartYear + iStartMonth;
iEndDate = iEndYear + iEndMonth;
iDateDiff = iEndDate – iStartDate;

if (iDateDiff >= 29) {
Calendar c = new GregorianCalendar();
String firstDate = strStartDate;
String secondDate = strEndDate;
DateFormat df = DateFormat.getDateInstance(DateFormat.SHORT);
Date fdate, sdate, newFDate;
try {
fdate = df.parse(firstDate);
sdate = df.parse(secondDate);
c.setTime(fdate);
c.add(Calendar.MONTH, 30);
log.debug("newFDate "+c.getTime());
newFDate = c.getTime();

if ( newFDate.after(sdate)||newFDate.equals(sdate) )
{
log.debug("newFDate is before the sdate");
log.debug("Difference is not more than 30 months");
return ("Success");
}}catch (ParseException e){
log.debug("error"+e);
}

log.debug("Difference is more than 30 months");
return ("Fail");
}
else
{
log.debug("Difference is not more than 30 months");
return ("Success");
}

}
}
[/code]

Method/Constructor : StrTokens

[code language=”java”]
import java.util.StringTokenizer;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

public class StrTokens {
private int iYear;
private int iMonth;
private int iDate;

/**
* @return Returns the iDate.
*/
public int getIDate() {
return iDate;
}
/**
* @param date The iDate to set.
*/
public void setIDate(int date) {
iDate = date;
}
/**
* @return Returns the iMonth.
*/
public int getIMonth() {
return iMonth;
}
/**
* @param month The iMonth to set.
*/
public void setIMonth(int month) {
iMonth = month;
}
/**
* @return Returns the iYear.
*/
public int getIYear() {
return iYear;
}
/**
* @param year The iYear to set.
*/
public void setIYear(int year) {
iYear = year;
}
public StrTokens(String strTxt, String strDelim)
{
String origTxt = new String();
String delimeter = new String();
int length = 0;
origTxt = strTxt;
delimeter = strDelim;
int delimLen = delimeter.length();
int startTokInd = 0;
int curDelimIndex = origTxt.indexOf(delimeter);
StringTokenizer str = new StringTokenizer(strTxt,strDelim);
int iCountTokens = str.countTokens();
String[] tokens = new String [iCountTokens];
int i=0;

while (str.hasMoreTokens())
{
tokens[i]=str.nextToken();
i++;
}
this.setIMonth(new Integer(tokens[0]).intValue());
this.setIYear(new Integer(tokens[2]).intValue());
this.setIDate(new Integer(tokens[1]).intValue());
}
}[/code]

The method getDateDiff will pass start date and end date to StrTokens constructor.
This constructor will parse the date and will obtain year, month and day part of given date.
The getDateDiff method then check if the date difference between start date and end date is more than 30 months. This method will then return a flag value indicating success/failure.

Top Related Articles:

  1. Java Year class explained with examples
  2. Java Date and Time
  3. Java ZoneOffset class explained with examples
  4. Java LocalDate
  5. How to Call a Method in Java

Tags: Java-Date

About the Author

I have 15 years of experience in the IT industry, working with renowned multinational corporations. Additionally, I have dedicated over a decade to teaching, allowing me to refine my skills in delivering information in a simple and easily understandable manner.

– Chaitanya

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Java Tutorial

Java Introduction

  • Java Index
  • Java Introduction
  • History of Java
  • Features of Java
  • C++ vs Java
  • JDK vs JRE vs JVM
  • JVM - Java Virtual Machine
  • First Java Program
  • Variables
  • Data Types
  • Operators

Java Flow Control

  • Java If-else
  • Java Switch-Case
  • Java For loop
  • Java while loop
  • Java do-while loop
  • Continue statement
  • break statement

Java Arrays

  • Java Arrays

OOPs Concepts

  • OOPs Concepts
  • Constructor
  • Java String
  • Static keyword
  • Inheritance
  • Types of inheritance
  • Aggregation
  • Association
  • Super Keyword
  • Method overloading
  • Method overriding
  • Overloading vs Overriding
  • Polymorphism
  • Types of polymorphism
  • Static and dynamic binding
  • Abstract class and methods
  • Interface
  • Abstract class vs interface
  • Encapsulation
  • Packages
  • Access modifiers
  • Garbage Collection
  • Inner classes
  • Static import
  • Static constructor

Java Exception Handling

  • Exception handling
  • Java try-catch
  • Java throw
  • Java throws
  • Checked and Unchecked Exceptions
  • Jav try catch finally
  • Exception Examples
  • Exception Propagation

Collections Framework

  • Collections in Java
  • Java ArrayList
  • Java LinkedList
  • Java Vector
  • Java HashSet
  • Java LinkedHashSet
  • Java TreeSet
  • Java HashMap
  • Java TreeMap
  • Java LinkedHashMap
  • Java Queue
  • Java PriorityQueue
  • Java Deque
  • Comparable interface
  • Comparator interface
  • Collections Interview Questions

MORE ...

  • Java Scanner Class
  • Java 8 Features
  • Java 9 Features
  • Java Conversion
  • Java Date
  • Java Multithreading
  • Java I/O
  • Java Serialization
  • Java Regex
  • Java AWT
  • Java Swing
  • Java Enum
  • Java Annotations
  • Java main method
  • Java Interview Q

Copyright © 2012 – 2025 BeginnersBook . Privacy Policy . Sitemap