|
Java™ by example!
|
|
|
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!
|
|
|
|
|