[java] How to convert a String to a Date using SimpleDateFormat?

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?

This question is related to java datetime date-format simpledateformat

The answer is


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

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();
    }

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);

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());
            }

    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.

Links


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();
    }

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 

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"


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()));

Examples related to java

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How much should a function trust another function How to implement a simple scenario the OO way Two constructors How do I get some variable from another class in Java? this in equals method How to split a string in two and store it in a field How to do perspective fixing? String index out of range: 4 My eclipse won't open, i download the bundle pack it keeps saying error log

Examples related to datetime

Comparing two joda DateTime instances How to format DateTime in Flutter , How to get current time in flutter? How do I convert 2018-04-10T04:00:00.000Z string to DateTime? How to get current local date and time in Kotlin Converting unix time into date-time via excel Convert python datetime to timestamp in milliseconds SQL Server date format yyyymmdd Laravel Carbon subtract days from current date Check if date is a valid one Why is ZoneOffset.UTC != ZoneId.of("UTC")?

Examples related to date-format

Format JavaScript date as yyyy-mm-dd How to format date in angularjs Rails formatting date How to change date format using jQuery? How to format Joda-Time DateTime to only mm/dd/yyyy? Java SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'") gives timezone as IST Display current time in 12 hour format with AM/PM java.util.Date format conversion yyyy-mm-dd to mm-dd-yyyy How to get a particular date format ('dd-MMM-yyyy') in SELECT query SQL Server 2008 R2 Converting a string to a date in a cell

Examples related to simpledateformat

How to convert an Instant to a date format? Get Date Object In UTC format in Java How to format a java.sql.Timestamp(yyyy-MM-dd HH:mm:ss.S) to a date(yyyy-MM-dd HH:mm:ss) How to convert date to string and to date again? Java Convert GMT/UTC to Local time doesn't work as expected Java SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'") gives timezone as IST SimpleDateFormat parse loses timezone java.text.ParseException: Unparseable date Java format yyyy-MM-dd'T'HH:mm:ss.SSSz to yyyy-mm-dd HH:mm:ss SimpleDateFormat returns 24-hour date: how to get 12-hour date?