2012-03-30 23 views
0

我要轉換字符串日期格式,但以下方式不起作用。將字符串轉換爲日期類型

它爲birth產生null


Date birth; 
try { 
    DateFormat formatter ; 
    formatter = new SimpleDateFormat("dd-MMM-yyyy"); 
    birth = (Date)formatter.parse(birthDate); // birtDate is a string 
} catch (ParseException e) { 
    System.out.println("Exception :"+e); 
} 
+1

這個出生日的價值是什麼? – Venki 2012-03-30 14:36:07

+1

爲什麼不使用喬達時間? – Venki 2012-03-30 14:37:08

+0

birthDate =「10-Jun-2005」; – aisheh90 2012-03-30 14:40:25

回答

2

你的答案是正確的金錢。我把它放在一個完整的程序中並進行測試。
現在打印出

Default date format Fri Mar 30 00:00:00 CDT 2012 
Our SimpleDateFormat 30-Mar-2012 
Our SimpleDateFormat with all uppercase 30-MAR-2012 

這裏有一些提示:

  • 確保您包括正確進口。根據 類路徑中的內容,您可能會意外導入了 java.sql.Date或其他一些流氓導入。
  • 嘗試進入try塊之前打印生日的內容 並驗證它確實 包含格式DD-MMM-YYYY的字符串

-

import java.text.DateFormat; 
import java.text.ParseException; 
import java.text.SimpleDateFormat; 
import java.util.Date; 

public class BirthDate { 

    public static void main(String[] args) { 
     Date birth = null; 
     String birthDate = "30-MAR-2012"; 
     DateFormat formatter = null; 
     try { 
      formatter = new SimpleDateFormat("dd-MMM-yyyy"); 
      birth = (Date) formatter.parse(birthDate); // birtDate is a string 
     } 
     catch (ParseException e) { 
      System.out.println("Exception :" + e); 
     } 
     if (birth == null) { 
      System.out.println("Birth object is still null."); 
     } else { 
      System.out.println("Default date format " + birth); 
      System.out.println("Our SimpleDateFormat " + formatter.format(birth)); 
      System.out.println("Our SimpleDateFormat with all uppercase " + formatter.format(birth).toUpperCase()); 
     } 
    } 
} 
+0

感謝它的工作:) – aisheh90 2012-03-30 15:04:28

+0

但你知道如何顯示它沒有00:00:00 CDT ?? – aisheh90 2012-03-30 15:05:37

+0

當然,我只是更新了答案,以便它再次使用SimpleDateFormat對象也以相同的格式打印出日期。 SimpleDateFormat對象可用於解析日期和打印日期。 – 2012-03-30 15:22:18

0

你的代碼工作正常。如果你喜歡使用喬達時間,你可以使用這個。如果您計劃使用時間進行數據庫測試和工作,您可以閱讀文檔以釋放完整的功能。

import org.joda.time.DateTime; 
DateTime dt = new DateTime("YYYY-MM-DD");//new DateTime("2012-03-30") 
System.out.println(dt);