Tim*_*Tim 26 java date deprecated
我可以用什么来取代它new Date(2009, 12, 9)?
谢谢你的帮助.
Jon*_*eet 25
理想情况下,使用Joda Time代替.它是内置的无限优越的API.然后,您会希望选择java.time并LocalDateTime根据您的具体要求(这是一个复杂的领域-我不打算尝试在一两句话来概括,但文档做好).
如果绝对必要,请使用java.util.Calendar并DateTime在需要时将其转换为.
Max*_*AMM 25
Calendar cal = Calendar.getInstance();
cal.set(2009, Calendar.DECEMBER, 12);
Run Code Online (Sandbox Code Playgroud)
请注意,我12月份没有12,因为它实际上是11(1月是0).
然后,您可以轻松地添加或删除秒,分钟,小时,天,月或年:
cal.add(Calendar.HOUR, 2);
cal.add(Calendar.MONTH, -5);
Run Code Online (Sandbox Code Playgroud)
最后,如果你想要一个日期:
cal.getTime();
Run Code Online (Sandbox Code Playgroud)
pjp*_*pjp 17
从JDK版本1.1开始,由Calendar.set(年份+ 1900,月份,日期,小时,分钟)或GregorianCalendar(年份+ 1900,月份,日期,小时,分钟)替换.
如果你看一下Date构造函数参数,你会看到它被弃用的原因:
参数:
Run Code Online (Sandbox Code Playgroud)year - the year minus 1900. month - the month between 0-11. date - the day of the month between 1-31. hrs - the hours between 0-23. min - the minutes between 0-59.
year不是你所期望的,也不是month.
要表示您提到的日期,您需要Date像这样打电话(不推荐)
new Date(2009-1900, 12-1, 9)
Run Code Online (Sandbox Code Playgroud)
替代使用Calendar是
Calendar cal = Calendar.getInstance();
cal.set(2009, 11, 9); //year is as expected, month is zero based, date is as expected
Date dt = cal.getTime();
Run Code Online (Sandbox Code Playgroud)
您还可以使用SimpleDateFormat对象:
import java.util.Date;
import java.text.SimpleDateFormat;
import java.text.ParseException;
public class DateTest {
public static void main( String [] args ) throws ParseException {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy, MM, dd");
Date date = sdf.parse("2009, 12, 9");
System.out.println( date );
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
47296 次 |
| 最近记录: |