簡體   English   中英

java SimpleDateFormat在Windows上返回部分時間

[英]java SimpleDateFormat returns a part of the time on windows

我正在嘗試獲取當前時間,並將其附加到我生成的文件的名稱中。

代碼段:

DateTimeFormatter dtf = DateTimeFormatter.ofPattern(app.values.getProperty("yyyy-MM-dd"));
LocalDateTime now = LocalDateTime.now();
String date = dtf.format(now);
Date today = Calendar.getInstance().getTime();
SimpleDateFormat timeFormat = new SimpleDateFormat("hh:mm");
String time = timeFormat.format(today);
FileOutputStream fs = new FileOutputStream("receipt/Receipt_" + date + "_"+time+".pdf");

這在linux上工作正常(文件名返回“ Receipt_2018-04-18_11:13”),但是當我在Windows 7上運行jar時,它只能給出

Receipt_2018-04-18_11

並且生成的文件已損壞且為空。 我怎樣才能解決這個問題?

問題在於,“:”是Windows操作系統上文件名的錯誤字符,因此需要替換。 基本上,您的代碼過多,您不需要Calendar因為LocalDateTime已經具有時間戳了。

DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd_hh_mm");
LocalDateTime now = LocalDateTime.now();
String dateTime = dtf.format(now);
FileOutputStream fs = new FileOutputStream("receipt/Receipt_" + dateTime + ".pdf");

希望能幫助到你!

SimpleDateFormat timeFormat = new SimpleDateFormat("hh:mm");
String time = timeFormat.format(today);
FileOutputStream fs = new FileOutputStream("receipt/Receipt_" + date + "_"+time+".pdf");

:是非法文件字符(至少在Windows下,可能是其他字符)。

有關更多信息,請查看命名文件,路徑和命名空間 ,其中包含無效文件/目錄名稱字符的列表。

例如,也許將其更改為-

SimpleDateFormat timeFormat = new SimpleDateFormat("hh-mm");
String time = timeFormat.format(today);
FileOutputStream fs = new FileOutputStream("receipt/Receipt_" + date + "_"+time+".pdf");

或使用SimpleDateFormat timeFormat = new SimpleDateFormat("hhmm"); 代替

更新

因此,顯然對於某些人來說,解決眼前的問題還遠遠不夠。

通常認為java.util.Date類已棄用,例如,您應該改用較新的(和改進的) java.time API。

DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd_hh-mm");
FileOutputStream fs = new FileOutputStream("receipt/Receipt_" + formatter.format(LocalDateTime.now()) + ".pdf");

或者,如果不能(使用Java 8+),請使用許多可用的庫之一,包括java.time的后端口

試試這個,我認為它將與您合作

對於java.util.Date,只需創建一個新的Date()

DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");    Date date = new Date();     System.out.println(dateFormat.format(date));

暫無
暫無

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

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