How to convert a String to a Date using SimpleDateFormat?

JavaDatetimeDate FormatSimpledateformat

Java Problem Overview


I have this code snippet:

DateFormat formatter1;
formatter1 = new SimpleDateFormat("mm/DD/yyyy");
System.out.println((Date)formatter1.parse("08/16/2011"));

When I run this, I get this as the output:

Sun Jan 16 00:10:00 IST 2011

I expected:

Tue Aug 16 "Whatever Time" IST 2011

I mean to say I am not getting the month as expected. What is the mistake?

Java Solutions


Solution 1 - Java

Try this:

new SimpleDateFormat("MM/dd/yyyy")
  • MM is "month" (not mm)
  • dd is "day" (not DD)

It's all in the javadoc for SimpleDateFormat


FYI, the reason your format is still a valid date format is that:

  • mm is "minutes"
  • DD is "day in year"

Also, you don't need the cast to Date... it already is a Date (or it explodes):

public static void main(String[] args) throws ParseException {
    System.out.println(new SimpleDateFormat("MM/dd/yyyy").parse("08/16/2011"));
}

Output:

Tue Aug 16 00:00:00 EST 2011

Voila!

Solution 2 - Java

m - min M - Months

Letter	Date or Time Component	Presentation	Examples
G   	Era designator   	    Text        		AD
y   	Year            	    Year        		1996; 96
M   	Month in year   	    Month       		July; Jul; 07
w   	Week in year    	    Number       		27
W   	Week in month   	    Number       		2
D   	Day in year     	    Number      		189
d   	Day in month    	    Number      		10
F   	Day of week in month	Number       		2
E   	Day in week     	    Text        		Tuesday; Tue
a   	Am/pm marker    	    Text        		PM
H   	Hour in day (0-23)	    Number      		0
k   	Hour in day (1-24)	    Number       		24
K   	Hour in am/pm (0-11)	Number      		0
h   	Hour in am/pm (1-12)	Number      		12
m   	Minute in hour   	    Number      		30
s   	Second in minute	    Number      		55
S   	Millisecond     	    Number       	 	978
z   	Time zone       	    General time zone	Pacific Standard Time; PST; GMT-08:00
Z   	Time zone       	    RFC 822 time zone	-0800 

Solution 3 - Java

Use the below function

/**
	 * Format a time from a given format to given target format
	 * 
	 * @param inputFormat
	 * @param inputTimeStamp
	 * @param outputFormat
	 * @return
	 * @throws ParseException
	 */
	private static String TimeStampConverter(final String inputFormat,
			String inputTimeStamp, final String outputFormat)
			throws ParseException {
		return new SimpleDateFormat(outputFormat).format(new SimpleDateFormat(
				inputFormat).parse(inputTimeStamp));
	}

Sample Usage is as Following:

	try {
		String inputTimeStamp = "08/16/2011";

		final String inputFormat = "MM/dd/yyyy";
		final String outputFormat = "EEE MMM dd HH:mm:ss z yyyy";

		System.out.println(TimeStampConverter(inputFormat, inputTimeStamp,
				outputFormat));

	} catch (ParseException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	}

Solution 4 - Java

String newstr = "08/16/2011";
SimpleDateFormat format1 = new SimpleDateFormat("MM/dd/yyyy");
SimpleDateFormat format = new SimpleDateFormat("EE MMM dd hh:mm:ss z yyyy");
Calendar c = Calendar.getInstance();
c.setTime(format1.parse(newstr));
System.out.println(format.format(c.getTime()));

Solution 5 - Java

Very Simple Example is.

SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd-MM-yyyy");
                Date date = new Date();
		        Date date1 = new Date();
			try {
				System.out.println("Date1:   "+date1);
				System.out.println("date" + date);

				date = simpleDateFormat.parse("01-01-2013");
				date1 = simpleDateFormat.parse("06-15-2013");

				System.out.println("Date1 is:"+date1);
				System.out.println("date" + date);

			} catch (Exception e) {
				System.out.println(e.getMessage());
			}

Solution 6 - Java

This piece of code helps to convert back and forth

    System.out.println("Date: "+ String.valueOf(new Date()));
    SimpleDateFormat dt = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    String stringdate = dt.format(new Date());
    System.out.println("String.valueOf(date): "+stringdate);

    try {
    Date date = dt.parse(stringdate);
    System.out.println("parse date: "+ String.valueOf(date));
    } catch (ParseException e) {
    e.printStackTrace();
    }

Solution 7 - Java

you can solve the problem much simple like First convert the the given string to the date object eg:

java.util.Date date1 = new Date("11/19/2015"); 
SimpleDateFormat formatter = new SimpleDateFormat("MMM dd yyyy HH:mma");
String format = formatter.format(date);
System.out.println(format);

Solution 8 - Java

	DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern("MM/dd/uuuu");
	System.out.println(LocalDate.parse("08/16/2011", dateFormatter));

Output:

> 2011-08-16

I am contributing the modern answer. The answer by Bohemian is correct and was a good answer when it was written 6 years ago. Now the notoriously troublesome SimpleDateFormat class is long outdated and we have so much better in java.time, the modern Java date and time API. I warmly recommend you use this instead of the old date-time classes.

What went wrong in your code?

When I parse 08/16/2011 using your snippet, I get Sun Jan 16 00:08:00 CET 2011. Since lowercase mm is for minutes, I get 00:08:00 (8 minutes past midnight), and since uppercase DD is for day of year, I get 16 January.

In java.time too format pattern strings are case sensitive, and we needed to use uppercase MM for month and lowercase dd for day of month.

Question: Can I use java.time with my Java version?

Yes, java.time works nicely on Java 6 and later and on both older and newer Android devices.

  • In Java 8 and later and on new Android devices (from API level 26, I’m told) the modern API comes built-in.
  • In Java 6 and 7 get the ThreeTen Backport, the backport of the new classes (ThreeTen for JSR 310; see the links at the bottom).
  • On (older) Android use the Android edition of ThreeTen Backport. It’s called ThreeTenABP. And make sure you import the date and time classes from org.threeten.bp with subpackages.

Solution 9 - Java

String localFormat = android.text.format.DateFormat.getBestDateTimePattern(Locale.getDefault(), "EEEE MMMM d");
return new SimpleDateFormat(localFormat, Locale.getDefault()).format(localMidnight);

will return a format based on device's language. Note that getBestDateTimePattern() returns "the best possible localized form of the given skeleton for the given locale"

Solution 10 - Java

You have used some type errors. If you want to set 08/16/2011 to following pattern. It is wrong because,

mm stands for minutes, use MM as it is for Months

DD is wrong, it should be dd which represents Days

Try this to achieve the output you want to get ( Tue Aug 16 "Whatever Time" IST 2011 ),

    String date = "08/16/2011"; //input date as String

    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("MM/dd/yyyy"); // date pattern

    Date myDate = simpleDateFormat.parse(date); // returns date object 

    System.out.println(myDate); //outputs: Tue Aug 16 00:00:00 IST 2011

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionShantanu TomarView Question on Stackoverflow
Solution 1 - JavaBohemianView Answer on Stackoverflow
Solution 2 - JavajahirView Answer on Stackoverflow
Solution 3 - JavaChand PriyankaraView Answer on Stackoverflow
Solution 4 - JavakandarpView Answer on Stackoverflow
Solution 5 - JavaKishan BheemajiyaniView Answer on Stackoverflow
Solution 6 - JavaAlfred Ayi-bonteView Answer on Stackoverflow
Solution 7 - JavaBEN SEBASTIANView Answer on Stackoverflow
Solution 8 - JavaOle V.V.View Answer on Stackoverflow
Solution 9 - JavaDan AlboteanuView Answer on Stackoverflow
Solution 10 - JavaDu-LacosteView Answer on Stackoverflow