【已解决】Eclipse中用java代码去new Date结果出错:The constructor Date(String) is deprecated

【背景】

折腾:

【未解决】Eclipse中调试Java代码期间如何修改值

期间,用代码:

Date newExpiryDate = new Date("Thu Sep 17 14:22:08 CST 2043");

结果出错:

The constructor Date(String) is deprecated 

如图:

The constructor Date(String) is deprecated

即:

The constructor Date(String) is deprecated

【解决过程】

1.很明显,Date过期了,不能用了。

所以去找替代者是啥。

2.参考:

The constructor Date(…) is deprecated. What does it mean? (Java)

去找找关于如何使用Calendar的。

3.找到:

Class Calendar

再去试试:

Calendar newExpiryCalendar = new Calendar();

结果又出错:

Cannot instantiate the type Calendar

所以,再参考之前的:

Class Calendar

找到:

Class GregorianCalendar

去改为:

Calendar newExpiryCalendar = new GregorianCalendar();

然后对于上面的时间值:

Thu Sep 17 14:22:08 CST 2043

此处,去改为:

Calendar newExpiryCalendar = new GregorianCalendar(2043, 9, 17);

其中,时分秒就不要了,因为只是为了设置过期时间,所以细节不重要。

3.当然,非要写全,也是可以的:

Calendar newExpiryCalendar = new GregorianCalendar(2043, 9, 17, 14, 22, 8);

 

【总结】

Java中,不要在用过期的Date,而改用GregorianCalendar,对应的用法:

Constructor Summary
GregorianCalendar()

          Constructs a default GregorianCalendar using the current time in the default time zone with the default locale.
GregorianCalendar(int year, int month, int date)

          Constructs a GregorianCalendar with the given date set in the default time zone with the default locale.
GregorianCalendar(int year, int month, int date, int hour, int minute)

          Constructs a GregorianCalendar with the given date and time set for the default time zone with the default locale.
GregorianCalendar(int year, int month, int date, int hour, int minute, int second)

          Constructs a GregorianCalendar with the given date and time set for the default time zone with the default locale.
GregorianCalendar(Locale aLocale)

          Constructs a GregorianCalendar based on the current time in the default time zone with the given locale.
GregorianCalendar(TimeZone zone)

          Constructs a GregorianCalendar based on the current time in the given time zone with the default locale.
GregorianCalendar(TimeZone zone, Locale aLocale)

          Constructs a GregorianCalendar based on the current time in the given time zone with the given locale.

比如:

import java.util.GregorianCalendar;
Calendar newExpiryCalendar = new GregorianCalendar(2043, 9, 17, 14, 22, 8);

即可。



发表评论

电子邮件地址不会被公开。 必填项已用*标注

无觅相关文章插件,快速提升流量