Convert string to Date in java
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.. Any help I would really appreciate. thanks
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
当我在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());
尝试这个
链接地址: http://www.djcxy.com/p/3044.html上一篇: 我如何运行Windows GUI应用程序作为服务?
下一篇: 在java中将字符串转换为Date