Home » Java Date & Time programs

How to convert Date string to Date format in Java?

SimpleDateFormat.parse() method in Java: In this program, we will learn how to convert Date string to Date format in Java?

Given a Date in string format and we have to convert given date in Date format.

Following package will be used in this program:

java.text.SimpleDateFormat

To define the input format and parse the input date in Date format.

Here, we will create an object of SimpleDateFormat() class to define the input format (which we are defining "dd/MM/yyyy"). Then create another object of Date class, assign the result returned by calling parse() method of SimpleDateFormat() class.

Consider the program:

/*java program to get current system date and time*/
import java.text.SimpleDateFormat;
import java.util.*;

public class ConvDateString2DatePrg 
	{
	public static void main(String args[])
		{
		try
		{
			//define date format to take input
			SimpleDateFormat dateF = new SimpleDateFormat("dd/MM/yyyy");


			Scanner sc=new Scanner(System.in);  //string object
			String dtString="";

			System.out.print("Enter date in dd/MM/yyyy format:");
			dtString=sc.nextLine();

			//convert input date string into Date
			Date dt= dateF.parse(dtString);

			System.out.print("Entered Date is: " + dt.toString());
		}
		catch(Exception e) {
			System.out.println("Exception is: "+ e.toString());
		}
	}
}

Output

Enter date in dd/MM/yyyy format:21/09/2008
Entered Date is: Sun Sep 21 00:00:00 IST 2008




Comments and Discussions




Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.