簡體   English   中英

將 SimpleDateFormat 轉換為字符串

[英]Converting SimpleDateFormat to String

我讓用戶輸入日期,輸入的日期是SimpleDateFormat dd-MM-yyyy 我將它保存在一個類對象中,然后想顯示它。 當我在JOptionPane消息框中顯示它時,它顯示如下內容:

java.text.SimpleDateFormat@9586200

什么可能導致這種情況,或者如何將其轉換為字符串並顯示? 這是我將輸入的日期從字符串轉換為日期的代碼。 現在我將fDate存儲到SimpleDateFormat flightDate; 在對象中。

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 = (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;

^是我想要顯示日期的方式。 我將如何轉換回String flightDate被聲明為SimpleDateFormat flightDate; 並且日期是從 try-catch 中的代碼分配給它的。

我非常懷疑您是否真的想將任何內容設置為SimpleDateFormat 我希望您將其設置為由SimpleDateFormat解析Date ,您當前忽略的返回值:

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

(您的setFlightDate方法應該接受DateCalendar ,而不是DateFormat 。)

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

稍后要將Date轉換回字符串,您可以使用format而不是parse

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

順便說一句,當List<Flight>更明智時,您似乎正在使用數組。 此外,您可能需要考慮使用Joda Time ,這是一個更好的日期/時間 API。

希望這有幫助,將其轉換為字符串。 像下面這樣:

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

你的程序有錯誤。 請參閱下面的更新代碼(注意變量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);
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM