問題描述
我正在嘗試做一些非常簡單的事情,但開始意識到 Java 中的日期有點雷區.我想要的只是通過三個整數組(一年、一個月和一個日期)創建一些 Date
對象,對它們進行一些簡單的測試(沿著日期 B 之前的日期 A并且在 1990 年 1 月 1 日之后),將它們轉換為 java.sql.Date
對象并通過 JDBC 將它們傳遞給數據庫.
I'm trying to do something really simple, but starting to realize that dates in Java are a bit of minefield. All I want is to get passed groups of three ints ( a year, a month and a date) create some Date
objects, do some simple test on them (along the lines of as date A before date B and after January 1 1990), convert them to java.sql.Date
objects and pass them off to the database via JDBC.
一切都非常簡單,使用 java.util.Date(int year,int month,int day)
構造函數可以正常工作.當然,該構造函數已被折舊,我想避免在我正在編寫的新代碼中使用折舊調用.然而,解決這個簡單問題的所有其他選項似乎都非常復雜.如果不使用折舊的構造函數,真的沒有簡單的方法可以做我想做的事嗎?
All very simple and works fine using the java.util.Date(int year,int month,int day)
constructor. Of course that constructor is depreciated, and I'd like to avoid using depreciated calls in new code I'm writing. However all the other options to solve this simple problem seem stupidly complicated. Is there really no simple way to do what I want without using depreciated constructors?
我知道所有 Java 日期相關問題的標準答案是使用 joda 時間",但我真的不想因為這樣一個看似微不足道的問題而開始使用第三方庫.
I know the standard answer to all Java date related questions is "use joda time", but I really don't want to start pulling in third party libraries for such a seemingly trivial problem.
推薦答案
想法是使用 Calendar
類,像這樣:
The idea is to use the Calendar
class, like so:
Calendar cal = Calendar.getInstance();
cal.set(year, month, date);
Date date = cal.getTime();
確實,如果您檢查 constructor 您提到的,正是建議的內容:
Indeed, if you check the Javadoc of the constructor you are mentioning, it is exactly what is suggested:
Date(int year, int month, int date)
Deprecated. As of JDK version 1.1, replaced by Calendar.set(year + 1900, month, date) or GregorianCalendar(year + 1900, month, date).
或者...使用 JodaTime :-).
Or ... use JodaTime :-).
這篇關于替換 java.util.Date(year,month,day) 的公認方法是什么的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!