Sunday, 23 February 2020

Java | Calculate number of days between two dates

In this tutorial, we will see how to calculate the number of days between two dates. This solution for the Java 7 version or below.

Program to find the number of Days between two Dates.

Steps:
1. Take dates input as Strings.
2. Parse the input string dates 'Date'.
3. Finds the difference between them in milliseconds.
4. Convert the milliseconds into Days.
5. Displays the result as output.

package com.algorithmforum.date;

import java.util.Date;
import java.text.SimpleDateFormat;

class DateDifference {
            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();
                        }
            }
}

No comments:

Post a Comment

Related Posts Plugin for WordPress, Blogger...