1

sample string is: 25-11-2015 14:59

String str= "25-11-2015 14:59";

I want to convert the str to Date. But it gives me an error. My conversion function is

public Date getDate(String date)
    {
        try {

            Log.v("Date","Date string: "+date);

            SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy hh:mm:ss");
            Date convertedDate = new Date();
            convertedDate = dateFormat.parse(date);
            return  convertedDate;

        } catch (Exception e)
        {
            Log.v("error","error date parse : "+e.getMessage());
            return  null;
        }
    }

But it showing error :

Unparseable date: "25-11-2015 14:59" (at offset 16)

can anyone help me where is the problem

2
  • Use dd-MM-yyyy HH:mm instead of dd-MM-yyyy hh:mm:ss. Commented Nov 25, 2015 at 9:43
  • That code works for me. I'm using Java 1.8. Commented Nov 25, 2015 at 10:10

3 Answers 3

2

Your format pattern should probably be: dd-MM-yyyy HH:mm. hh is for "Hour in am/pm (1-12)", as detailed in the javadoc.

Sign up to request clarification or add additional context in comments.

Comments

0

You may create some generic thing and check the length ;

public  static Date getDate(String date){
     Date convertedDate = null;

        DateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss aa");

        if (date.length() == 16)            
            dateFormat = new SimpleDateFormat("dd-MM-yyyy HH:mm");
        else if (date.length() == 10)
            dateFormat = new SimpleDateFormat("dd-MM-yyyy"); 

        try {
            convertedDate = dateFormat.parse(date); 
        } catch (ParseException e) {
            e.printStackTrace();

        }
    return convertedDate;
}

Comments

0

Code explanation of assylias by considering your requirement :)

      String testDateString2 = "02-04-2014 23:37";    
      SimpleDateFormat df2 = new SimpleDateFormat("dd-MM-yyyy HH:mm"); 
      Date d2 = df2.parse(testDateString2);
      System.out.println("Date : "+df2.format(d2));

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.