How to convert String to Date in java whatever system format is
This question already has an answer here:
You're trying to convert a String in EEEE, MMMM dd, yyyy
format with the format of dd/MM/yyyy
...
Start by using the correct format for the String
you trying to convert, the use what ever format you want to convert it back...
SimpleDateFormat from = new SimpleDateFormat("EEEE, MMMM dd, yyyy");
SimpleDateFormat to = new SimpleDateFormat("dd/MM/yyyy");
String value = to.format(from.parse(dateString));
Now you could use something like DateUtils.parseDate(String, String[])
which allows to supply a number of different formats, but is still limited to what you might know.
A better solution would be to store the Date
value directly within the database.
Try to use something like this:
public static String dateToString(String date){
if(date.equals("")) return "";
if(date == null || date.length() == 0){
return "";
}
SimpleDateFormat formatIn = new SimpleDateFormat("dd/MM/yyyy");
SimpleDateFormat formatOut = new SimpleDateFormat("yyyy-dd-MM");
try {
Date l_date = formatIn.parse(date);
String result = formatOut.format(l_date);
return result;
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return "";
}
}
but if you want to put some data into database you may also use instead String java.sql.Date
something like this:
SimpleDateFormat format = new SimpleDateFormat();
Connection conn = ...
PreparedStatement ps = conn.prepareStatement("...");
long lDate = format.parse(sDate).getTime();
java.sql.Date dDate = new java.sql.Date(lDate);
ps.setDate(1, dDate);
链接地址: http://www.djcxy.com/p/84546.html
上一篇: Java在Mac OS X上安装在哪里?