Monday 1 June 2020

JAVA Tutorial | Easiest Way To Get List Of Dates Between Two Dates






Code :-


import java.text.SimpleDateFormat;
import java.util.*;

public class DateList {
   
    public static void main(String[] args) throws Exception {
        String from="2020-01-01";
        String to="2020-05-30";
       
        Date d_from = new SimpleDateFormat("yyyy-MM-dd").parse(from);
        Date d_to = new SimpleDateFormat("yyyy-MM-dd").parse(to);
       
        //System.out.println(d_from.getTime());
       
        long t1=d_from.getTime();
        long t2=d_to.getTime();
       
        SimpleDateFormat f=new SimpleDateFormat("yyyy-MM-dd");
       
        if(t1<t2)
        {
            //1 = 1000
            for(long i=t1;i<=t2;i+=86400000)
            {
                System.out.println(f.format(i));
            }
        }
       
    }
   
}


------------------------------------------------
Please avoid or flag spams/hateful comments. And do not spam. Enjoy :)
------------------------------------------------


Subscribe my Channel:-
http://www.youtube.com/user/SanketRooney?sub_confirmation=1

Facebook Page:-
https://www.facebook.com/UnpossibleNS

Twitter Account:-
https://twitter.com/UnpossiblePOG

Blog :-
https://unpossiblepog.blogspot.in/
------------------------------------------------

Hey guys.
In this video, I shall show you the easiest way to get list of dates between two dates in JAVA.
Here I am using netbeans IDE and the date format as year-month and date.

 I shall be converting string to date by using date and SimpleDateFormat classes.
With netbeans, you will be assisted to import required packages and handle exceptions.

However, I shall manually handle exception by throwing it in main function line.
Main strategy is to convert date into milliseconds.

Now using LONG as data type is important because the milliseconds are large numbers.
First thing I shall do is to verify if from-date is lesser than to-date by applying if statement.

Now, I shall use for loop, a variable start with from-date and stop at to-date.
In for loop, I shall add 1 day in milliseconds.
One day is 86400 second.
However, 1 second equals to 1000 milliseconds, so add more three zeros.

Let check the output.

Now, the only thing left is to convert milliseconds to date.
For that, SimpleDateFormat variable is required.
Use format function with 1 argument of milliseconds.

The JAVA code handles even a leap as you can see, 29 days in February. 2020 which is the worst year.

The code link is given in the description.
Don’t forget to like, share and subscribe.
Thanks for watching. 


No comments:

Post a Comment