問題描述
我正在嘗試做一些非常簡單的事情,但開始意識到 Java 中的日期有點雷區(qū).我想要的只是通過三個整數(shù)組(一年、一個月和一個日期)創(chuàng)建一些 Date
對象,對它們進(jìn)行一些簡單的測試(沿著日期 B 之前的日期 A并且在 1990 年 1 月 1 日之后),將它們轉(zhuǎn)換為 java.sql.Date
對象并通過 JDBC 將它們傳遞給數(shù)據(jù)庫.
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)
構(gòu)造函數(shù)可以正常工作.當(dāng)然,該構(gòu)造函數(shù)已被折舊,我想避免在我正在編寫的新代碼中使用折舊調(diào)用.然而,解決這個簡單問題的所有其他選項似乎都非常復(fù)雜.如果不使用折舊的構(gòu)造函數(shù),真的沒有簡單的方法可以做我想做的事嗎?
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 日期相關(guān)問題的標(biāo)準(zhǔn)答案是使用 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:
確實,如果您檢查 constructor 您提到的,正是建議的內(nèi)容:
Indeed, if you check the Javadoc of the constructor you are mentioning, it is exactly what is suggested:
或者...使用 JodaTime :-).
Or ... use JodaTime :-).
這篇關(guān)于替換 java.util.Date(year,month,day) 的公認(rèn)方法是什么的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網(wǎng)!