java怎样将字符型的日期转为日期型插入到数据库中
我在jsp中定义了一个文本框用来接收日期,怎样在Servlet中接收并将其转为日期型插入到数据库中啊...
我在jsp中定义了一个文本框用来接收日期,怎样在Servlet中接收并将其转为日期型插入到数据库中啊
展开
2个回答
展开全部
//yyyy-MM-dd hh:mm:ss
public static Date dateTimeString2Date(String date_str) {
try {
Calendar cal = Calendar.getInstance();
java.sql.Timestamp timestampnow = new java.sql.Timestamp(cal.getTimeInMillis());
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
ParsePosition pos = new ParsePosition(0);
java.util.Date current = formatter.parse(date_str, pos);
timestampnow = new java.sql.Timestamp(current.getTime());
return timestampnow;
}
catch (NullPointerException e) {
return null;
}
}
//格式以上面不一样yyyy-MM-dd
public static Date dateString2Date(String date_str) {
try {
Calendar cal = Calendar.getInstance();
java.sql.Timestamp timestampnow = new java.sql.Timestamp(cal.getTimeInMillis());
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
ParsePosition pos = new ParsePosition(0);
java.util.Date current = formatter.parse(date_str, pos);
return current;
}
catch (NullPointerException e) {
return null;
}
}
至于插入数据库,可以用java.sql.PreparedStatement;
public static Date dateTimeString2Date(String date_str) {
try {
Calendar cal = Calendar.getInstance();
java.sql.Timestamp timestampnow = new java.sql.Timestamp(cal.getTimeInMillis());
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
ParsePosition pos = new ParsePosition(0);
java.util.Date current = formatter.parse(date_str, pos);
timestampnow = new java.sql.Timestamp(current.getTime());
return timestampnow;
}
catch (NullPointerException e) {
return null;
}
}
//格式以上面不一样yyyy-MM-dd
public static Date dateString2Date(String date_str) {
try {
Calendar cal = Calendar.getInstance();
java.sql.Timestamp timestampnow = new java.sql.Timestamp(cal.getTimeInMillis());
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
ParsePosition pos = new ParsePosition(0);
java.util.Date current = formatter.parse(date_str, pos);
return current;
}
catch (NullPointerException e) {
return null;
}
}
至于插入数据库,可以用java.sql.PreparedStatement;
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询