Showing posts with label Calendar. Show all posts
Showing posts with label Calendar. Show all posts

Monday, September 7, 2026

Find Number of Days Between Two Dates in Java

Find Number of Days Between Two Given Dates in Java

Sometimes we need to find the number of days between two given dates. Earlier, I used Calendar and manually calculated the difference between the dates.

With Java 8 and later, this can be done much more easily using the java.time package.

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;

public class FindDays {

    public static void main(String[] args) {

        String str1 = "20/01/2013";
        String str2 = "28/03/2013";

        DateTimeFormatter formatter =
                DateTimeFormatter.ofPattern("dd/MM/yyyy");

        LocalDate date1 = LocalDate.parse(str1, formatter);
        LocalDate date2 = LocalDate.parse(str2, formatter);

        long days = ChronoUnit.DAYS.between(date1, date2);

        System.out.println("Final Days.... " + days);
    }
}

Output:

Final Days.... 67

How it works

DateTimeFormatter is used to tell Java the format of the input dates.

LocalDate represents a date without a time or timezone.

ChronoUnit.DAYS.between() calculates the number of days between the two dates.

For example:

20/01/2013 → 28/03/2013 = 67 days

The older Calendar approach can still be found in existing Java applications, but for new development, the java.time API is generally the better choice.


Friday, November 11, 2016

How to Convert a String Date to Java Calendar

How to convert String date to Java Calendar.


This can be done by some other way also, but  I have done in the below format. Hope this is will help you.

 

Example :- 
Input String Date - "20160829T23:59:59Z"

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

public class StringDateToCalendar {

    /**
     * @param args
     */
    public static void main(String[] args) throws Exception {
            String string = "20160829T23:59:59Z";
            String pattern = "yyyyMMdd'T'HH:mm:ss'Z'";
            Date date = new SimpleDateFormat(pattern).parse(string);
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(date);
            System.out.println("Calendar is :: "+ calendar.getTime());
    }

}
Output :-
Calendar is :: Mon Aug 29 23:59:59 AEST 2016