2016-08-23 120 views
-1

我想字符串转换为日期我的JDBC program.I曾尝试以下方法转换字符串到日期JAVA

 DateFormat Formatter=null; 
     Date convertedDate=null; 
     Formatter=new SimpleDateFormat("DD-MMM-YYYY",Locale.ENGLISH); 
     try { 
      convertedDate=(Date)Formatter.parse(date); 
     } catch (ParseException e1) { 
      // TODO Auto-generated catch block 
      e1.printStackTrace(); 
     } 
     java.sql.Date sqlDate=new java.sql.Date(convertedDate.getTime()); 
     System.out.println(date); 
     System.out.println(convertedDate); 

我现在面临的问题是,例如,如果我传递'30 - NOV-2001'作为参数,当我使用DateFormat将其转换为Date并将其存储在convertedDate中时,我得到“Sun Dec 31 00:00:00 IST 2000”作为明显错误的输出。所以请帮助我在这。

+3

与格式化尝试=新的SimpleDateFormat(” DD-MMM-YYYY”,Locale.ENGLISH); – SpringLearner

+2

[如同格式化,请检查您使用的格式是什么意思...](http://docs.oracle.com/javase/6/docs/api/java/text/SimpleDateFormat.html) – SomeJavaGuy

回答

2

你需要使用"dd-MMM-yyyy"

DateFormat Formatter=null; 
     Date convertedDate=null; 
     Formatter=new SimpleDateFormat("DD-MMM-YYYY",Locale.ENGLISH); 
     try { 
      convertedDate=(Date)Formatter.parse(date); 
     } catch (ParseException e1) { 
      // TODO Auto-generated catch block 
      e1.printStackTrace(); 
     } 
     java.sql.Date sqlDate=new java.sql.Date(convertedDate.getTime()); 
     System.out.println(date); 
     System.out.println(convertedDate); 

d表示天,在今年 d表示天在一个月

Oracle docs更多信息

+0

谢谢它的作品:) –

+0

@SaiSankalp我很高兴 – SpringLearner

+0

是的,我接受了答案。再次感谢您的帮助:) –