I'm trying to parse a string to a date field in an android application but I can't seem to get it correct. Here is the string I'm trying to convert to a date "03/26/2012 11:49:00 AM". The function I'm using is:
private Date ConvertToDate(String dateString){ SimpleDateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy hh:mm:ss aa"); Date convertedDate = new Date(); try { convertedDate = dateFormat.parse(dateString); } catch (ParseException e) { // TODO Auto-generated catch block e.printStackTrace(); } return convertedDate; }
But I keep getting 3/1/112 11:49AM
as the result.
By default, Java dates are in the ISO-8601 format, so if we have any string which represents a date and time in this format, then we can use the parse() API of these classes directly.
You are wrong in the way you display the data I guess, because for me:
String dateString = "03/26/2012 11:49:00 AM"; SimpleDateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy hh:mm:ss aa"); Date convertedDate = new Date(); try { convertedDate = dateFormat.parse(dateString); } catch (ParseException e) { // TODO Auto-generated catch block e.printStackTrace(); } System.out.println(convertedDate);
Prints:
Mon Mar 26 11:49:00 EEST 2012
it went OK when i used Locale.US
parametre in SimpleDateFormat
String dateString = "15 May 2013 17:38:34 +0300"; System.out.println(dateString); SimpleDateFormat dateFormat = new SimpleDateFormat("dd MMM yyyy HH:mm:ss Z", Locale.US); DateFormat targetFormat = new SimpleDateFormat("dd MMM yyyy HH:mm", Locale.getDefault()); String formattedDate = null; Date convertedDate = new Date(); try { convertedDate = dateFormat.parse(dateString); System.out.println(dateString); formattedDate = targetFormat.format(convertedDate); } catch (ParseException e) { // TODO Auto-generated catch block e.printStackTrace(); } System.out.println(convertedDate);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With