简体   繁体   English

将字符串 dd/MM/yyyy 日期转换为 java.sql.date yyyy-MM-dd

[英]Convert String dd/MM/yyyy date into java.sql.date yyyy-MM-dd

I am using the below method to do the described conversion.我正在使用以下方法进行所描述的转换。 But the java.sql.Date method is deprecated.但是java.sql.Date方法已被弃用。 So, is their any harm in using this method?那么,他们使用这种方法有什么危害吗? As the statements below are working fine.由于下面的语句工作正常。

(Retrieving value of date as string in servlet from session and then storing the date in MySQL.) (从会话中检索 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))); 

You should use SimpleDateFormat (or the equivalent from Joda Time ) rather than trying to parse this yourself:您应该使用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());

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM