Tuesday 14 July 2020

Quickest & Easiest Way To Sort Date Array In Java




Quickest way to sort date-time array in JAVA.



------------------------------------------------
Code :

package tutorials;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Set;
import java.util.TreeSet;

public class SortDateTime {
    public static void main(String[] args) throws ParseException {
        String dateArray[]={
            "2019-01-02 03:05",
            "2019-01-02 03:05",
            "2019-01-02 03:00",
            "2019-01-02 05:00",
            "2019-01-01 15:00",
            "2018-05-05 00:30",
            "2020-04-03 40:00",
            "2020-02-01 59:00"
        };
        SimpleDateFormat f=new SimpleDateFormat("yyyy-MM-dd HH:mm");
       
        Set<Long> s=new TreeSet<Long>();
       
        for(int i=0;i<dateArray.length;i++)
        {
            s.add(f.parse(dateArray[i]).getTime());
        }
       
        for(Long l:s)
        {
            System.out.println(f.format(l));
        }
       
    }
}

------------------------------------------------
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, we shall sort date-time array in java in the quickest and easiest way possible.
This technique has one drawback which i shall explain at the ending of this video.
I already created a file and inside it there is a string array which has format of like date-time.
I am recommending you to use netbeans as it provides auto-suggestions.
We are going to need a SimpleDateFormat class.
Import required package.
Then we are using set & treeset with LONG as data-type.
In for loop, we are going to find out the length of array and add each array element in set.
but before that, we are converting date-string  into long number using simpledateformat’s function called getTime().

The SET class already ordered data in ascending order.
Then we are going to use FOR:EACH loop.
and in that, we call each data and again convert long into Date-time format.

As per input and output, 2018 should be at the top.
Also, if date is same but hours and minutes are different, then also those values get sorted.

The only drawback of this technique is that, it skips one element if that same element is already present in array.

Code link & other required links are given in the description.
Don’t forget to like, share and subscribe.
Thanks for watching. 


No comments:

Post a Comment