在java中将string转换为Date

我试图parsing一个string的android应用程序中的date字段,但我似乎无法得到正确的。 这是我想转换为“03/26/2012 11:49:00 AM”date的string。 我正在使用的function是:

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; } 

但我不断得到3/1/112 11:49 AM作为结果..任何帮助,我真的很感激。 谢谢

你猜错我显示数据的方式,因为对我来说:

  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); 

打印:

 Mon Mar 26 11:49:00 EEST 2012 

当我在SimpleDateFormat使用Locale.US参数时,它就OK了

 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); 
 String str_date="13-09-2011"; DateFormat formatter ; Date date ; formatter = new SimpleDateFormat("dd-MM-yyyy"); date = (Date)formatter.parse(str_date); System.out.println("Today is " +date.getTime()); 

尝试这个

这段代码将帮助你做出如FEB 17 20:49的结果。

  String myTimestamp="2014/02/17 20:49"; SimpleDateFormat form = new SimpleDateFormat("yyyy/MM/dd HH:mm"); Date date = null; Date time = null; try { date = form.parse(myTimestamp); time = new Date(myTimestamp); SimpleDateFormat postFormater = new SimpleDateFormat("MMM dd"); SimpleDateFormat sdf = new SimpleDateFormat("HH:mm"); String newDateStr = postFormater.format(date).toUpperCase(); String newTimeStr = sdf.format(time); System.out.println("Date : "+newDateStr); System.out.println("Time : "+newTimeStr); } catch (Exception e) { e.printStackTrace(); } 

结果:

date:二月十七日

时间:20:49

 GregorianCalendar date; CharSequence dateForMart = android.text.format.DateFormat.format("yyyy-MM-dd", date); Toast.makeText(LogmeanActivity.this,dateForMart,Toast.LENGTH_LONG).show(); 
 SimpleDateFormat formatter = new SimpleDateFormat("dd/MM/yyyy"); String dateInString = "07/06/2013"; try { Date date = formatter.parse(dateInString); System.out.println(date); System.out.println(formatter.format(date)); } catch (ParseException e) { e.printStackTrace(); } 

输出:

 2014/08/06 16:06:54 2014/08/06 16:06:54