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 – Calculate number of days between two dates

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

In this tutorial we will see how to calculate the number of days between two dates.

Program to find the number of Days between two Dates

In this program we have the dates as Strings. We first parses them into Dates and then finds the difference between them in milliseconds. Later we are convert the milliseconds into Days and displays the result as output.

Note: In Java 8 we can easily find the number of days between the given dates using a simple java method. Refer this Java 8 tutorial to check this program in Java 8

import java.util.Date;
import java.text.SimpleDateFormat;
class Example{
   public static void main(String args[]){
	 SimpleDateFormat myFormat = new SimpleDateFormat("dd MM yyyy");
	 String dateBeforeString = "31 01 2014";
	 String dateAfterString = "02 02 2014";

	 try {
	       Date dateBefore = myFormat.parse(dateBeforeString);
	       Date dateAfter = myFormat.parse(dateAfterString);
	       long difference = dateAfter.getTime() - dateBefore.getTime();
	       float daysBetween = (difference / (1000*60*60*24));
               /* You can also convert the milliseconds to days using this method
                * float daysBetween = 
                *         TimeUnit.DAYS.convert(difference, TimeUnit.MILLISECONDS)
                */
	       System.out.println("Number of Days between dates: "+daysBetween);
	 } catch (Exception e) {
	       e.printStackTrace();
	 }
   }
}

Output:

Number of Days between dates: 2.0

In the above example, we have the dates in the format of dd MM yyyy and we are calculating the difference between them in days. If you have dates in the different format then you need to change the code a little bit. For example if you have the dates in this format “MM/dd/yyyy” then you need to replace the first three lines of the code (inside main method) with this code:

SimpleDateFormat myFormat = new SimpleDateFormat("MM/dd/yyyy");
String dateBeforeString = "01/31/2014";
String dateAfterString = "02/02/2014";

 

Related Posts:

  1. Java – parse the date in desired format
  2. Java – Convert the String to 24 hrs date time format
  3. Java – current date and time
  4. Java – SimpleDateFormat

Top Related Articles:

  1. Date validation in java
  2. Java 8 – Calculate days between two dates
  3. Java Access Modifiers – Public, Private, Protected & Default
  4. Compare two dates with each other in Java
  5. Date Formatting In Java With Time Zone

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

Comments

  1. Frank says

    March 10, 2014 at 5:55 PM

    The above example does not factor daylight savings and leap years. Very important issue in the real world.

    Reply
  2. Carlos FC says

    March 21, 2014 at 10:56 PM

    Try this case, and does not work (Java 6 u 35):

    Calendar cal1 = new GregorianCalendar();
    Calendar cal2 = new GregorianCalendar();
    cal1.set(2014, 3, 3);
    cal2.set(2014, 3, 6);

    System.out.println(“Days= “+ ( (cal2.getTime().getTime() – cal1.getTime().getTime()) / (1000 * 60 * 60 * 24)));

    Reply
  3. karan says

    December 23, 2014 at 2:51 PM

    Above method is not giving correct output.
    I have given dates “01-31-2014” and “02-02-2014”
    output is -1 which is wrong.It should be 2.

    Reply
    • Chaitanya Singh says

      October 17, 2017 at 1:15 PM

      I have updated the guide with a new code. A new way to find the number of days between two dates.

      Reply
  4. Neeraj Kumar says

    December 29, 2014 at 10:09 AM

    hi guys i am using this is code but here is some error.
    String index out of range: 10

    Reply
    • Chaitanya Singh says

      October 17, 2017 at 1:15 PM

      Try the new code and let me know if you still face the issue.

      Reply

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