how to create Date object from String value

19,700

Solution 1

You used wrong dateformat for month, also you should use the same delimiter as in your date.

If you date string is of format "2013/01/03"

use the same delimiter / for the pattern "yyyy/MM/dd"

If your date string is of format "2013-01-03"

use the same delimiter '-' in your pattern "yyyy-MM-dd"

    DateFormat df = new SimpleDateFormat("yyyy/mm/dd"); 

should be

    DateFormat df = new SimpleDateFormat("yyyy/MM/dd"); 

From SimpleDateFormat Doc

MM---> month in an year

mm---> minutes in hour

Solution 2

MM instead of mm

- instead of / ie yyyy-MM-dd as you are using - in date string

Solution 3

String startDateString = "2013-03-26";
DateFormat df = new SimpleDateFormat("yyyy/MM/dd"); 

you are using different pattern than what you are parsing.

either initialize this as DateFormat df = new SimpleDateFormat("yyyy-MM-dd"); or this as String startDateString = "2013/03/26";

also look this article

Share:
19,700
Hussain Akhtar Wahid 'Ghouri'
Author by

Hussain Akhtar Wahid 'Ghouri'

in.linkedin.com/pub/hussain-akhtar-wahid/40/657/274/ https://www.facebook.com/hussain.a.wahid

Updated on June 04, 2022

Comments

  • Hussain Akhtar Wahid 'Ghouri'
    Hussain Akhtar Wahid 'Ghouri' almost 2 years

    When running through the below code I am getting an UNPARSABLE DATE EXCEPTION.

    How do I fix this?

       package dateWork;
    
        import java.text.DateFormat;
        import java.text.ParseException;
        import java.text.SimpleDateFormat;
        import java.util.Date;
    
        public class DateCreation {
    
            /**
             * @param args
             */
            public static void main(String[] args) {
    
                String startDateString = "2013-03-26";
                DateFormat df = new SimpleDateFormat("yyyy/MM/dd"); 
                Date startDate=null;
                String newDateString = null;
                try 
                {
                    startDate = df.parse(startDateString);
                    newDateString = df.format(startDate);
                    System.out.println(startDate);
                } catch (ParseException e) 
                {
                    e.printStackTrace();
                }
            }
    
        }