转换日期格式

我得到'14-Dec-2010'日期我希望得到给定日期的数字格式的月份。 也就是说,我希望将日期转换为'14-12-2010'

 DateFormat inFm = new SimpleDateFormat("d-MMM-y"); DateFormat outFm = new SimpleDateFormat("dM-yyyy"); Date date = inFm.parse("14-Dec-2010"); String output = outFm.format(date); 

通常,您应该在内部使用Date类的Date类型,然后在输出时转换为String

 import java.text.SimpleDateFormat; import java.util.Date; public class DateFormatter { /** * @param args */ public static void main(String[] args) { Date date = new Date("14-Dec-2010"); //deprecated. change it to your needs DateFormat df = new SimpleDateFormat("dd-MM-yyyy"); System.out.println(df.format(date)); } } 

我认为这个SQL转换应该工作

SELECT CONVERT(datetime,’14 -Dec-2010’,105)

 DateFormat format = new SimpleDateFormat("dd-MMM-yyyy"); Date date= format.parse("14-Dec-2010"); 

现在,您可以使用任何格式打印日期对象。
注意 :月份从0开始,因此对于Dec ,它将是11

  • 这是IDE One演示
  • 文件

避免使用与最早版本的Java捆绑在一起的麻烦的旧日期时间类。 它们的设计很差,令人困惑。

java.time

旧类被java.time框架取代。

对于没有时间且没有时区的仅日期值,请使用LocalDate类。

使用DateTimeFormatter解析String输入。

 String input = "14-Dec-2010"; DateTimeFormatter formatter = DateTimeFormatter.ofPattern( "dd-MMM-yyyy" ); LocalDate localDate = LocalDate.parse( input , formatter ); 

要以其他格式生成String,请定义另一个格式化程序。

 DateTimeFormatter formatter2 = DateTimeFormatter.ofPattern( "dd-MM-yyyy" ); String output = localDate.format( formatter2 ); 

更好的是,让DateTimeFormatter自动本地化。

 Locale l = Locale.CANADA_FRENCH ; // Or Locale.US, Locale.ITALY, etc. DateTimeFormatter f = DateTimeFormatter.ofLocalizedDate( FormatStyle.SHORT ).withLocale( l ); String output = localDate.format( f ); // Generates String in a localized format. 

SQL

对于SQL只传递对象,不要使用字符串。 如果JDBC驱动程序符合JDBC 4.2规范,则在PreparedStatement上通过setObject传递LocalDate

 myPrepStmt.setObject( localDate ); 

如果没有,请使用添加到旧类的新转换方法回退到旧的java.sql.Date类。

 java.sql.Date sqlDate = java.sql.Date.from( localDate ); myPrepStmt.setDate( sqlDate );