2010-12-14 158 views
2

我得到的日期爲'14-Dec-2010'我想在給定的日期得到數字格式的月份。即,我想將日期轉換爲'14-12-2010'轉換日期格式

回答

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

這就是你如何得到Date對象,現在你可以用任何格式打印它。
注意:一個月從0開始,所以Dec這將是11

+0

它不工作,並給出了異常:java.text.ParseException:無法解析的日期:「12月14日 - 2010 – 2010-12-14 07:45:50

+0

@hilal,對我的作品(OpenJDK的Java 1.6的) – 2010-12-14 07:47:50

+0

我沒有做任何事情。不同的只是複製和粘貼:)並且它不起作用。你的代碼也不適用於我。我不知道它引發異常的原因java.text.ParseException:Unparseable date:「14-Dec -2010" 。(OpenJDK java 1.6) – 2010-12-14 07:52:28

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

一般來說,你應該使用的datetime型像Date內部,然後在輸出時轉換爲String

+0

它將打印14-11-2010我認爲 – 2010-12-14 07:44:45

+0

@org,不,它不會;嘗試一下。 SimpleDateFormat知道使用基於1的索引。你可能想到'Calendar',它使用了基於0的月份索引。 – 2010-12-14 07:46:39

+0

是觀察到它謝謝 – 2010-12-14 08:00:02

1
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)); 

    } 

} 
+0

該構造函數已被棄用。最好明確你所期望的格式。 – 2010-12-14 07:40:55

1

我覺得這個SQL轉換應該工作

SELECT CONVERT(日期時間,'14 - 癸2010' ,105),所用的最早的捆綁麻煩的舊日期時間類

0

避免Java版本。他們設計不好,令人困惑。

java.time

老班由java.time框架所取代。

對於僅包含日期的值,沒有時區使用LocalDate類。

使用DateTimeFormatter解析字符串輸入。

String input = "14-Dec-2010"; 

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

要以另一種格式生成字符串,請定義另一個格式程序。

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規範,則通過通過setObjectPreparedStatement上。

myPrepStmt.setObject(localDate); 

如果沒有,使用添加到老班新的轉換方法回落到老java.sql.Date類。

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