java.date 废弃,Java中的Date(String)的不被废弃的完全等价物?

这篇博客探讨了如何解决Java中Date构造函数被弃用的问题。作者建议使用SimpleDateFormat来解析日期字符串,以保持与旧代码相同的行为。在尝试转换时,博客提到了可能遇到的ParseException,并给出了相应的异常处理策略。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

I have old code that uses new Date(dateString) to parse a date string. Compiling the code produces the deprecation warning Date(java.lang.String) in java.util.Date has been deprecated.

The javadoc unhelpfully advises me to use DateFormat.parse(), even though the DateFormat class does not have a static parse method.

Now, I know how to use SimpleDateFormat, but I want to make sure I'm getting the exact same behaviour of the deperecated Date constructor.

解决方案

Here's my guess (I posted as community wiki so you can vote up if I'm right):

Date parsed = new Date();

try {

SimpleDateFormat format =

new SimpleDateFormat("EEE MMM dd HH:mm:ss zzz yyyy");

parsed = format.parse(dateString);

}

catch(ParseException pe) {

throw new IllegalArgumentException();

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值