Extract Date from a String in Java

Hey Everyone! In this article, we will learn how to Extract a Date from a user-entered String in Java.


We will be using the date class in Java to parse the String inputted by the user in Java.
The Date class is present in java.util.Date package. The Date class in Java provides constructors and methods to handle Date and Time in Java.

Date Class in Java


The Date class in Java is used to interpret the date in year, month, day, hour, minute and second values. It is used to format and parse (i.e extract) date from strings in a format specified. Let us look at the code to understand the Date class in Java.
Two methods viz parse and format is used together to extract the date from the user entered String.

Java Code To extract a Date from a User-entered String

package program;

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

public class Program {

   
    public static void main(String[] args) 
    {
        String dt = new String();
        Scanner sc =  new Scanner(System.in);
        System.out.println("Enter a String containing a date in yyyy-mm-dd format only");
        dt=sc.nextLine();
        
        
        
      try 
      {    
          //Format for string is specified here and passed as a parameter in the constructor
      Date sdf = new SimpleDateFormat("yyyy-MM-dd").parse(dt);
      //Two methods viz parse and format are used to extract Date from the string
      String date = new SimpleDateFormat("dd/MM/yyyy").format(sdf);
       System.out.println("The date is "+date+" (dd/mm/yyyy) ");
      } 
    catch (Exception e) {
        System.out.println("Exception occured "+e);
     }
        
        
    }
    
}

 

Output:-

run:
Enter a String containing a date in yyyy-mm-dd format only
1999-04-20
The date is 20/04/1999
BUILD SUCCESSFUL (total time: 10 seconds)

I hope this article was useful/helpful to you. Please leave a comment down below in case of any doubts or suggestions.

Also read: How To Subtract Days to Date in Java

Leave a Reply

Your email address will not be published. Required fields are marked *