問題描述
有沒有一種直接的方法可以將 Java SQL 日期從 yyyy-MM-dd 格式轉換為 dd MMMM yyyy 格式?
Is there a straightforward way of converting a Java SQL Date from format yyyy-MM-dd to dd MMMM yyyy format?
我可以將日期轉換為字符串,然后對其進行操作,但我寧愿將其保留為 Java SQL 日期.在我需要這樣做的時候,數據已經從 MySQL 數據庫中讀取,所以我不能在那里進行更改.
I could convert the date to a string and then manipulate it but I'd rather leave it as a Java SQL Date. at the time I need to do this, the data has already been read from the MySQL database so I cant do the change there.
推薦答案
java.sql.Date
和java.util.Date
等對象(其中java.sql.Date
是一個子類)沒有自己的格式.您使用 java.text.DateFormat
對象以特定格式顯示這些對象,并且是 DateFormat
(不是 Date
本身)確定格式.
Object such as java.sql.Date
and java.util.Date
(of which java.sql.Date
is a subclass) don't have a format of themselves. You use a java.text.DateFormat
object to display these objects in a specific format, and it's the DateFormat
(not the Date
itself) that determines the format.
例如:
Date date = ...; // wherever you get this
DateFormat df = new SimpleDateFormat("dd MMMM yyyy");
String text = df.format(date);
System.out.println(text);
注意:當您打印 Date
對象而不使用 DateFormat
對象時,如下所示:
Note: When you print a Date
object without using a DateFormat
object, like this:
Date date = ...;
System.out.println(date);
然后它將使用一些默認格式進行格式化.但是,該默認格式不是您可以更改的 Date
對象的屬性.
then it will be formatted using some default format. That default format is however not a property of the Date
object that you can change.
這篇關于將 Java SQL 日期從 yyyy-MM-dd 轉換為 dd MMMM yyyy 格式的最佳方法的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!