esuslogo
 [To advertise Java(tm) Events here, contact joris@esus.com!]
banner

Java™
by example!






New @ Esus.com


  gb  In-house search engine for better results!

  gb  Get updates with the esus.com
newsletter!









  Home 
 Browse Categories 
 Ask a Java Question 
 Help 
  For Java Tips & Tricks, subscribe to the esus.com newsletter!
Search Java Q&A, Links, API's:   adv 

What do I use to create a Date from a String, as that Date constructor has been deprecated?
Use the parse function of aa DateFormat or a SimpleDateFormat object to parse the string into the correct date. You must of course know the format of the string, which you use to configure the formatter object. I've only personally used the SimpleDateFormat class (which is a concrete implementation of the abstract DateFormat class), as it allows you to configure the format pattern for any date format in the constructor (the API mentions doing the same for a DateFormat object using applyPattern(), but I didn't see it).

eg. converting a string of form d/M/yyyy into a Date object.

 
BufferedReader reader = new BufferedReader(new InputStreamReader(inStream));

String inputDate = reader.readLine();

// The constructor is the format the string will take
SimpleDateFormat formatter = new SimpleDateFormat("d/M/yyyy");
Date lineDate = formatter.parse(inputDate);


You can also use a ParsePosition object to tell the formatter which element of the string to start from, and it on completion the ParsePosition object will contain the position the formatter finished on, or the start if formatting failed.

eg. Getting a date object for strings of format "DATE IS: d/M/yyyy"

 
BufferedReader reader = new BufferedReader(new InputStreamReader(inStream));
ParsePosition pos = new ParsePosition(8);

String inputDate = reader.readLine();

SimpleDateFormat formatter = new SimpleDateFormat("d/M/yyyy");
Date dateTest = formatter.parse(inputDate, pos);


The parse() method returns null if unsuccessful, so you should perform a check with an if() statement to see if the date was created.

See the API page on SimpleDateFormat for details on symbols for different date patterns.


Further Information
Author of answer: TreeFidi

Comments to this answer are only viewable by members. Login or become a member!





Terms of Service | Privacy Policy | Contact

Copyright © 2000-2003 Esus.com - All Rights Reserved 
Java and all Java-based trademarks are trademarks of Sun Microsystems, Inc. Esus.com is independent of Sun Microsystems, Inc. All other trademarks are the sole property of their respective owners.