2013-06-04 82 views
0

我有一個用戶輸入日期,輸入的日期是一個SimpleDateFormat。 DD-MM-YYYY。 我將它保存在一個Class對象中,然後想要顯示它。 當我在JOptionPane消息框中顯示它時。它顯示了這一點。 [email protected] 什麼可能導致這種情況,或者如何將它轉換爲字符串並顯示它? 下面是我將從字符串輸入的日期轉換爲日期的代碼。 現在我將fDate存儲到SimpleDateFormat flightDate中;在對象中。SimpleDateFormat轉換爲字符串

try 
{ 
    SimpleDateFormat fDate = new SimpleDateFormat("dd-MM-yyyy"); 
    fDate.setLenient(false); 
    fDate.parse(dateText); 
    Main.flightObjects[Main.flightCount].setFlightDate(fDate); 
} 
catch(java.text.ParseException d) 
{ 
    JOptionPane.showMessageDialog(null, 
    "Please make sure your date is in the correct format! dd-mm-yyyy\n e.g. 16-03-2013", 
    "Date Error 1",1); 
} 

String dateS; 
    dateS = (String)flightDate.format(flightDate); 

    String output = "Flight num: " + flightNumber + "\nDate: " + dateS + "\nDeparting City: " + departCity + "\nArrival City: " + arriveCity + "\nAvailable Seats: " + seatsAvailable + "\nSold Seats: " + seatsSold + "\nSeat Price: R" + seatPrice; 

    return output; 

這^是我想要顯示的日期。我將如何轉換回字符串? flightDate被聲明爲SimpleDateFormat flightDate;並且在try catch中的代碼中分配了日期。 謝謝。

+0

'SimpleDateFormat'就是一個類從日期轉換爲字符串 –

回答

0

您的程序中有一個錯誤。請參閱更新的代碼如下(注意變量DATEVALUE):

try 
{ 
    SimpleDateFormat fDate = new SimpleDateFormat("dd-MM-yyyy"); 
    fDate.setLenient(false); 
    Date dateValue = fDate.parse(dateText); 
    Main.flightObjects[Main.flightCount].setFlightDate(dateValue); 
} 
catch(java.text.ParseException d) 
{ 
    JOptionPane.showMessageDialog(null, 
    "Please make sure your date is in the correct format! dd-mm-yyyy\n e.g. 16-03-2013", 
    "Date Error 1",1); 
} 
+0

謝謝。我沒有做日期dateValue = fDate ....部分。 –

2

我非常懷疑你真的想要設置任何東西到SimpleDateFormat。我希望你把它設置爲DateSimpleDateFormat解析,您目前忽略的返回值:

Main.flightObjects[Main.flightCount].setFlightDate(fDate.parse(dateText)); 

(你setFlightDate方法應該接受Date或許Calendar,不DateFormat。)

A SimpleDateFormat不是日期 - 它只是一個文本/日期轉換器。

要將Date轉換回字符串後,你會使用的format代替parse

String text = fDate.format(Main.flightObjects[Main.flightCount].getFlightDate()); 

順便說一句,它看起來像你使用數組時List<Flight>會更明智的。另外,您可能要考慮使用Joda Time這是一個更好的日期/時間API。

+0

喜;謝謝(你的)信息。 :-)但由於某種原因,我只是無法得到它的工作...: -/ 我做了一個eddit與我的顯示代碼。 –

+0

@EnthusedDragon:你沒有顯示'flightDate'的類型,但無論它是什麼類型,你都不應該試圖讓它自己格式化!您需要將Date變量傳遞給DateFormat.format。 –

0

希望這有助於將其轉換爲字符串。如下所示:

DateFormat df = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss"); 

// Get the date 
Date today = Calendar.getInstance().getTime();   
// Using DateFormat format method we can create a string 
String reportDate = df.format(today); 

// Print date or do what ever you like to do with it 
System.out.println("Report Date: " + reportDate);