最新消息:20210816 当前crifan.com域名已被污染,为防止失联,请关注(页面右下角的)公众号

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

Java crifan 8552浏览 0评论

【背景】

折腾:

【未解决】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);

即可。

转载请注明:在路上 » 【已解决】Eclipse中用java代码去new Date结果出错:The constructor Date(String) is deprecated

发表我的评论
取消评论

表情

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址
82 queries in 0.151 seconds, using 22.14MB memory