Sorting the date in ascending order in java

Question

Sorting the date given by the user in a day, month, year order. Sort them in ascending order and display them.

Sorting the date

Algorithm

  1. First get the list of dates from the user as a string.
  2. Create an array of objects for Date class and dynamically allocate memory.
  3. Create an object for SimpleDateFormat class with the format as “dd-MM-yyyy”.
  4. Parse the string dates to the date object.
  5. Sort the dates and print them.

Program

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.Scanner;

class DateSort
{
    public static void main(String as[]) throws ParseException
    {
        Scanner sc =new Scanner (System.in);
        Date date[];
        String str[];
        System.out.println("Enter no. of dates");               
        int i,n = sc.nextInt();                                 //integer input    
        str= new String[n];                                     //dynamic memory allocation for string of size of n
        date= new Date[n];                                      //dynamic memory allocation for date of size n
        sc.nextLine();                              
        
        for(i=0;i<n;i++)
        {                                           
            str[i]=sc.nextLine();                               //getting date as string from user
        }
        /*create object for SimpleDate format and
        spcify format for day-month-year as dd-MM-yyyy
        */
        SimpleDateFormat sobj = new SimpleDateFormat("dd-MM-yyyy");// format specified in double quotes
        
        for(i=0;i<n;i++)
        {
            date[i]=sobj.parse(str[i]);                         //parse the date string to date obj
        }
        /*import java.util.Arrays and sort the date[] array 
        using inbuilt sort method
        */
        Arrays.sort(date);                                                                            
        
        for(Date date1 : date)                                  //Enchanced for loop, it loops through all element in date array
        {                                                       //each time date[i] is copied to date1 like traditional for loop
            System.out.println(sobj.format(date1));             //format the date1 to dd-MM-yyyy using sobj 
        }
        
    }
}

 

Follow For Instant Updates

Join WhatsApp Group: link
Join our Telegram Channel: link
Like our Facebook Page:  link
Subscribe to our Youtube channel: link

Sree Hari Sanjeev

The founder of Wisdom Overflow. Software Developer at Zoho Corporation.
0 0 votes
Article Rating
Subscribe
Notify of
guest
5.4K Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
5.4K
0
Would love your thoughts, please comment.x
()
x