0

I have a date in 02/21/2013 04:52:10 PM this format.

How do I convert it into MM-dd-yyyy HH:mm. I already tried few things but it keeps throwing error

java.text.ParseException: Unparseable date: "02/21/2013 04:52:10 PM" (at offset 2)

I really need a help from date format expert. Thanks

user533844
  • 2,053
  • 7
  • 36
  • 43

3 Answers3

0

Construct two SimpleDateFormat objects. The first you parse() the value from into a Date object, the second you use to turn the Date object back into a string, e.g.

try {
  DateFormat df1 = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
  DateFormat df2 = new SimpleDateFormat("dd-MMM-yyyy");
  return df2.format(df1.parse(input));
}
catch (ParseException e) {
  return null;
}

Parsing can throw a ParseException so you would need to catch and handle that.

In addition, check this out:-

http://developer.android.com/reference/java/text/SimpleDateFormat.html

and more:-

http://msdn.microsoft.com/en-us/library/aa226054(SQL.80).aspx

and more:-

Date format conversion Android

Community
  • 1
  • 1
Philo
  • 1,931
  • 12
  • 39
  • 77
0

Try this one:

DateFormat inputFormat = new SimpleDateFormat("mm/dd/yyyy hh:mm:ss a", Locale.getDefault());
DateFormat outputFormat = new SimpleDateFormat("MM-dd-yyyy HH:mm", Locale.getDefault());

try {
    System.out.println("Converted: " + outputFormat.format(inputFormat.parse("02/21/2013 04:52:10 PM")));
} catch (ParseException e) {
    e.printStackTrace();
}

Output: 01-21-2013 16:52

Checkout http://docs.oracle.com/javase/1.4.2/docs/api/java/text/SimpleDateFormat.html for more

Cheers

Trinimon
  • 13,839
  • 9
  • 44
  • 60
0

You need verify if your String have / or - in the mask, case have / then you must used:

 SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss", LOCALE_BR);
Date convert = sdf.parse(data);     

case your String have - then you must used:

 SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", LOCALE_BR);
    Date convert = sdf.parse(data);   

Or then, use the replace() for change of the caracter - for /

Rodolfo Faquin
  • 810
  • 1
  • 8
  • 14