How to convert String to Date in Java

In Java we can use SimpleDateFormat API to format String to Date object. Here is one simple example to convert a String to Date object

Example

package com.pretech;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class StringtoDateConversion {
	public static void main(String[] args) {
		DateFormat formatter = new SimpleDateFormat("dd-MMM-yyyy");
		String dateInString = "12-Dec-2010";
		try {
			Date date = formatter.parse(dateInString);
			System.out.println("Date object is " + date);
		} catch (ParseException e) {
			e.printStackTrace();
		}
	}
}

Output



Date object is Sun Dec 12 00:00:00 IST 2010


No comments:

Post a Comment

12 classic String-based Java interview questions with simple explanations and code.

  1️⃣ Check if a String is a Palindrome Problem Given a string, check if it reads the same forward and backward. Example: "madam...

Featured Posts