Click to See Complete Forum and Search --> : Converting from String to Date data type


biosphere
December 20th, 2002, 03:42 AM
hi, can somebody give me some idea of how to convert a string data type to a date data type... thanks for the help given...

biosphere

dlorde
December 20th, 2002, 09:07 AM
Use the parse(...) (http://java.sun.com/j2se/1.4/docs/api/java/text/SimpleDateFormat.html#parse(java.lang.String,%20java.text.ParsePosition)) method of the java.text.SimpleDateFormat (http://java.sun.com/j2se/1.4/docs/api/java/text/SimpleDateFormat.html) class.

biosphere
December 22nd, 2002, 10:22 PM
hi dlorde,

thanks for the idea given earlier, anyway, can i know more about this ...parse(...) method, earlier i've try to used this parse method, but i found out this method is used together with the throw exeption which mean have to put into one function. (is this true?, correct me if i'm wrong) however, i wonder is there any other way, to convert a string data type to a date data type, or use that parse(...) method, in a direct manner, which mean make it work without a function... and byt the way, i am applying this date conversion in the web-based JSP... thanks again for the info given earlier...

biosphere

dlorde
December 23rd, 2002, 12:49 PM
biosphere - if you don't know how to use exceptions you won't get very far. Exceptions are fundamental to Java - I recommend the Java Tutorial (http://java.sun.com/docs/books/tutorial/) (exceptions (http://java.sun.com/docs/books/tutorial/essential/exceptions/)) and Bruce Eckel's online Java book 'Thinking in Java (http://www.codeguru.com/java/tij/tij_c.shtml)'.

The SimpleDateFormat.parse(...) method can be used like this:try {
String format = "MM/dd/yyyy"; // Use your own format here
// Make a date formatter
DateFormat df = new SimpleDateFormat(format);
// Convert the string to a date
Date theDate = df.parse(inputDateString);
... do something with the date
}
catch(ParseException pe) {
// do whatever is needed when the inputDateString doesn't
// match the required format.
}That's just one way of handling it, there are many variations on the theme.

If you are writing JSP, it is generally recommended that you don't put raw Java (scriptlets) into the JSP code, but you should use JSP Custom Tags to call your Java code. This implies that the date conversion code should go into a method that will be called from a custom tag.