Java parse String to Date

Learn to parse dates from string to java.util.Date object. Also see some useful date pattern strings, which will help you in building your own custom date pattern.

SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd-MMM-yyyy");
String dateString = "7-Jun-2013";

Date dateObj = simpleDateFormat.parse( dateString );		//String to Date

String dateStr = simpleDateFormat.format( dateObj );		//Date to String

Useful Date Patterns

PatternExample
yyyy-MM-dd (ISO)“2018-07-14”
dd-MMM-yyyy“14-Jul-2018”
dd/MM/yyyy“14/07/2018”
E, MMM dd yyyy“Sat, Jul 14 2018”
h:mm a“12:08 PM”
EEEE, MMM dd, yyyy HH:mm:ss a“Saturday, Jul 14, 2018 14:31:06 PM”
yyyy-MM-dd'T'HH:mm:ssZ“2018-07-14T14:31:30+0530”
hh 'o''clock' a, zzzz“12 o’clock PM, Pacific Daylight Time”
K:mm a, z“0:08 PM, PDT”

Checkout SimpleDateFormat to build your own custom patterns using date and time formatting symbols.

Date parsing example

Quick example to parse a String to Date obejct and vice-versa.

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

public class Main 
{
	public static void main(String[] args) throws ParseException 
	{
		SimpleDateFormat sdf = new SimpleDateFormat("dd-MMM-yyyy");
		String dateString = "14-Jul-2018";
		
		try 
		{
            Date date = sdf.parse(dateString);
            System.out.println(date);			//Sat Jul 14 00:00:00 IST 2018
            
            String dateStr = sdf.format(date);
            System.out.println(dateStr);		//14-Jul-2018
        } 
		catch (ParseException e) {
            e.printStackTrace();
        }
	}
}	

Happy Learning !!

Was this post helpful?

Join 7000+ Fellow Programmers

Subscribe to get new post notifications, industry updates, best practices, and much more. Directly into your inbox, for free.

Leave a Comment

HowToDoInJava

A blog about Java and its related technologies, the best practices, algorithms, interview questions, scripting languages, and Python.