Java Date object constructor for getting string is deprecated

穿精又带淫゛_ 提交于 2019-12-24 00:57:38

问题


I have problem using Date in java, I have a string that represent a date for example String date = "23/10/2012"; and i have a function that get a date as parameter, for example

public void foo(Date date){...}

my problem is that Date constructor that accept a string is deprecated and i do not want to use a deprecated object.


回答1:


So, you look at the Javadoc for the deprecated method which specifies:

Deprecated. As of JDK version 1.1, replaced by DateFormat.parse(String s).

You then look up DateFormat.parse and proceed accordingly. You probably want to create a SimpleDateFormat - or better still, use Joda Time which is a much better date/time API.

When a method is deprecated, it's always a good idea to give an indication of what existing code should be migrated to, and ideally why the old method was deprecated. Follow this guidance when you deprecate your own methods... and whenever you try to use a deprecated method, check the documentation to see if it suggests a better alternative.




回答2:


Use SimpleDateFormat.parse(String) to parse a string to java.util.Date object

String date = "23/10/2012"  
Date date = new SimpleDateFormat("dd/MM/yyyy").parse(date);



回答3:


You may need to use SimpleDatFormat (or) Joda library.

Example:

new SimpleDateFormat("dd/MM/yyyy").parse(yourDateString);


来源:https://stackoverflow.com/questions/13823797/java-date-object-constructor-for-getting-string-is-deprecated

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!