Date java lang string is deprecated

A non-deprecated exact equivalent of Date(String s) in Java?

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.

7 Answers 7

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

Date parsed; try < SimpleDateFormat format = new SimpleDateFormat("EEE MMM dd HH:mm:ss zzz yyyy"); parsed = format.parse(dateString); >catch(ParseException pe)

Yeah, that’s pretty much how I’d do it if I wanted to get exactly the same behaviour. The reason why DateFormat.getInstance() is better is it returns the appropriate formatter for the current locale.

Please, pretty please never, ever do a «new IllegalgArgumentException()» :O . At the very least chain the original exception (new IllegalArgumentException(pe)).

I had to use «new SimpleDateFormat(«EEE MMM dd HH:mm:ss zzz yyyy», Locale.ENGLISH);» to make this work — Just in case someone else is having problems.

FYI, these terrible date-time classes were supplanted a few years ago by the modern java.time classes defined in JSR 310.

SimpleDateFormat is the way to go. Can I point out, however, that you may feel compelled to define one SimpleDateFormat instance and build Date objects using this. If you do, beware that SimpleDateFormat is not thread-safe and you may be exposing yourself to some potentially hard-to-debug issues!

I’d recommend taking this opportunity to look at Joda which is a much better thought-out (and thread-safe) API. It forms the basis of JSR-310, which is the new proposed Java Date API.

I understand this is a bit more work. However it’s probably worthwhile given that you’re having to refactor code at the moment.

If you take a look at source of the Date.parse(String s) method that Nicolas mentions, you’ll see that it will be difficult or impossible to construct a date format that exactly reproduces the behavior.

Читайте также:  Parse json file with python

If you just want to eliminate the warning, you could put @SuppressWarnings() outside the method calling the Date(String) constructor.

If you really want to ensure future access to this behavior with future JREs, you might be able to just extract the method from the JDK sources and put it into your own sources. This would require a careful read of the source code licenses and consideration of their application to your specific project, and might not be permissible at all.

DateFormat has static methods that return DateFormat instances. I don’t know which one (if any) has the same behavior as Date(String s) but here you go:

DateFormat.getInstance() DateFormat.getDateInstance() DateFormat.getTimeInstance() DateFormat.getDateTimeInstance() 

Short answer (before further investigation) is: no, it is not equivalent. the Date(String toParse) constructor is equivalent to the parse method of the class Date (which is also deprecated). And the javadoc of this method claims:

Note that this is slightly different from the interpretation of years less than 100 that is used in SimpleDateFormat.

If it is the only change, I guess you can go on this way.

To parse a date time string in ISO format you should use the DateFormat like this:

With SimpleDateFormat you need to know the format.

Code only answers are discouraged. Please add some explanation as to how this solves the problem, or how this differs from the existing answers. From Review

This differs from the previous answers because it is a simple «one-line» answer that is tthe equivalent function of the one line in the original question. val dateObject = DateFormat.getDateInstance().parse(«string»)

tl;dr

ZonedDateTime.format( input , DateTimeFormatter.ofPattern( "EEE MMM dd HH:mm:ss zzz uuuu" , Locale.ENGLISH ) ) 

java.time

The terrible Date and DateFormat classes were supplanted years ago by the modern java.time classes with the adoption of JSR 310.

Читайте также:  Get with params java

The constructor you reference is actually calls on the static method Date.parse . As that documentation explains, that method takes a variety of formats. There is single point for the same behavior in java.time. However, I would doubt your app is encountering all those various format syntaxes simultaneously.

I suggest you look at the specific formats used by your actual data. Then craft a collection of DateTimeFormatter objects to match. Note that unlike the legacy classes, the java.time classes are entirely thread-safe. So you can keep one set of formatters around for use repeatedly throughout your app and across threads.

For the formatting pattern shown in the accepted Answer, here is the equivalent in java.time using the DateTimeFormatter class. Note that you should explicitly state your desired/expected locale rather than rely implicitly on the JVM’s current default locale.

DateTimeFormatter f = DateTimeFormatter.ofPattern( "EEE MMM dd HH:mm:ss zzz uuuu" , Locale.ENGLISH ) ; ZonedDateTime zdt = ZonedDateTime.format( input , f ) ; 

You should avoid using the legacy date-time classes such as java.util.Date wherever possible. But if you must have a Date to interoperate with old code not yet updated to java.time, you can convert. Look to new conversions methods added to the old classes.

The misnamed java.util.Date represents a moment in UTC. Its modern equivalent is the java.time.Instant class. We can extract an Instant from our ZonedDateTime . Then convert to a Date .

Instant instant = zdt.toInstant() ; // Adjust from time zone to UTC. java.util.Date d = Date.from( instant ) ; // Convert from modern class `Instant` to legacy class `Date`. 

Going the other direction.

Instant instant = d.toInstant() ; // Convert from legacy class `Date` to modern class `Instant`. ZonedDateTime zdt = instant.atZone( ZoneId.of( "Pacific/Auckland" ) ) ; // Adjust from UTC to the wall-clock time used by the people of a particular region (a time zone). 

About java.time

The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date , Calendar , & SimpleDateFormat .

To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.

Читайте также:  Pandas python загрузка excel

The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.

You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.* classes.

Where to obtain the java.time classes?

  • Java SE 8, Java SE 9, Java SE 10, Java SE 11, and later — Part of the standard Java API with a bundled implementation.
    • Java 9 adds some minor features and fixes.
    • Most of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
    • Later versions of Android bundle implementations of the java.time classes.
    • For earlier Android (<26), the ThreeTenABP project adapts ThreeTen-Backport (mentioned above). See How to use ThreeTenABP….

    The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval , YearWeek , YearQuarter , and more.

    Источник

    The constructor Date(String) is deprecated [duplicate]

    Using these lines in the scrips to read the cookies from the file. Yes, the «Date» is deprecated. I have read some solutions but still there are chain of errors while correcting it. What will be the correct one in the place of «date». Also I provide the full script below

    package test; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.util.Date; import java.util.StringTokenizer; import org.openqa.selenium.Cookie; import org.openqa.selenium.WebDriver; import org.openqa.selenium.chrome.ChromeDriver; public class Reader < public static void main(String[] args) < System.setProperty ("webdriver.chrome.driver", "D:\\Selenium\\chromedriver_win32\\chromedriver.exe"); WebDriver driver = new ChromeDriver(); driver.get("http://www.gmail.com"); try< File f = new File("browser.data"); FileReader fr = new FileReader(f); BufferedReader br = new BufferedReader(fr); String line; while ((line = br.readLine())!=null)< StringTokenizer str = new StringTokenizer (line, ";"); while (str.hasMoreTokens()) < String name = str.nextToken(); String value = str.nextToken(); String domain = str.nextToken(); String path = str.nextToken(); Date expiry = null; String dt; if(!(dt=str.nextToken()).equals("null")); < expiry = new Date(dt); >boolean isSecure = new Boolean(str.nextToken()).booleanValue(); Cookie ck = new Cookie (name,value,domain,path,expiry,isSecure); driver.manage().addCookie(ck); br.close(); > > > catch (Exception ex) < ex.printStackTrace(); >driver.get("http://gmail.com"); > > 

    Источник

Оцените статью