将String dd / MM / yyyy date转换为java.sql.date yyyy-MM-dd

时间:2012-03-08 20:53:45

标签: mysql date servlets

我使用以下方法进行所述转换。但不推荐使用java.sql.Date方法。那么,使用这种方法有什么害处吗?由于以下陈述工作正常。

(从会话中检索日期的值作为servlet中的字符串,然后将日期存储在MySQL中。)

String f33_ =(String)session.getAttribute(“sf33”);


java.sql.Date f33 = new java.sql.Date(Integer.parseInt(f33_.substring(6,10)) - 1900,Integer.parseInt(f33_.substring(3,5)) - 1,Integer .parseInt(f33_.substring(0,2)));

1 个答案:

答案 0 :(得分:1)

你应该使用SimpleDateFormat(或来自Joda Time的等价物),而不是试图自己解析:

DateFormat format = new SimpleDateFormat("dd/MM/yyyy", Locale.US);
format.setTimeZone(TimeZone.getTimeZone("Etc/UTC"));

java.util.Date date = format.parse(text);

java.sql.Date sqlDate = new java.sql.Date(date.getTime());
相关问题