Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert string to Date in java

Tags:

java

date

android

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.

like image 543
devman Avatar asked Mar 30 '12 14:03

devman


People also ask

Can we convert String to date in Java?

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.


2 Answers

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 
like image 152
Boris Strandjev Avatar answered Sep 19 '22 02:09

Boris Strandjev


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); 
like image 28
mDonmez Avatar answered Sep 20 '22 02:09

mDonmez