How to parse Date from String in the format: dd/MM/yyyy to dd/MM/yyyy in java?


The java.text package provides a class named SimpleDateFormat which is used to format and parse dates in required manner (local).

One of the constructors of this class accepts a String value representing the desired date format and constructors SimpleDateFormat object.

The format() method of this class accepts a java.util.Date object and returns a date/time string in the format represented by the current object.

Therefore, to parse a date String to another date format −

  • Get the input date string.

  • Convert it into java.util.Date object.

  • Instantiate the SimpleDateFormat class by passing the desired (new) format as string to its constructor.

  • Invoke the format() method by passing the above obtained Date object as parameter.

Example

 Live Demo

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Scanner;
public class FormattingDate {
   public static Date StringToDate(String dob) throws ParseException {
      //Instantiating the SimpleDateFormat class
      SimpleDateFormat formatter = new SimpleDateFormat("dd-MM-yyyy");
      //Parsing the given String to Date object
      Date date = formatter.parse(dob);
      System.out.println("Date object value: "+date);
      return date;
   }
   public static void main(String args[]) throws ParseException {
      //Reading name and date of birth from the user
      Scanner sc = new Scanner(System.in);
      System.out.println("Enter your name: ");
      String name = sc.next();
      System.out.println("Enter your date of birth (dd-MM-yyyy): ");
      String dob = sc.next();
      //Converting String to Date
      Date date = FormattingDate.StringToDate(dob);
      System.out.println("Select format: ");
      System.out.println("a: MM-dd-yyyy || b: dd-MM-yyyy || c: yyyy-MM-dd ");
      char ch = sc.next().toCharArray()[0];;
      switch (ch) {
         case 'a':
            System.out.println("Date in the format: MM-dd-yyyy");
            System.out.println(new SimpleDateFormat("MM-dd-yyyy").format(date));
            break;
         case 'b':
            System.out.println("Date in in the format: dd-MM-yyyy");
            System.out.println(new SimpleDateFormat("dd-MM-yyyy").format(date));
            break;
         case 'c':
            System.out.println("Date in the format: yyyy-MM-dd");
            System.out.println(new SimpleDateFormat("yyyy-MM-dd").format(date));
            break;
         default:
            System.out.println("Model not found");
            break;
      }
   }
}

Output

Enter your name:
Krishna
Enter your date of birth (dd-MM-yyyy):
26-09-1989
Date object value: Tue Sep 26 00:00:00 IST 1989
Select format:
a: MM-dd-yyyy || b: dd-MM-yyyy || c: yyyy-MM-dd
a
Date in the format: MM-dd-yyyy
09-26-1989

Updated on: 14-Oct-2019

12K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements