Re: Date question
- From: rhino_redux@xxxxxxxx
- Date: 29 Jun 2006 13:23:11 -0700
hoho123 wrote:
String dateStr = "01-May-2006"
I have a string of date like above, is there java class I can use to
make it a sql.date object?
Thank you!
There are a few classes that you could use in combination for this job,
specifically SimpleDateFormat, java.util.Date and java.sql.Date.
I had an existing method that did exactly that for a different date
format, namely ISO format. (Today would be "2006-06-29" in ISO format.)
I just modified my method to expect your format instead, wrote some
test cases for JUnit and gave it a try; it worked perfectly. Here's the
method, as revised to handle your date format:
/**
* Converts a date expressed as a String into a java.sql.Date.
*
* <p><i>Example:</i><br>
* <xmp>
* java.sql.Date mySqlDate =
DateTimeUtils.toSqlDate2("01-May-2006"); //should return an SQL date
equivalent to the input date.
* </xmp></p>
*
* <p><b>NOTE: </b>Although the input parameter expresses a date
with only a year, month and day,
* the date returned by this method includes a year, month, day,
hour, minute, second, and milliseconds.
* The date returned by this method will have the same year, month,
and day as the input parameters
* while the hours, minutes, seconds, and milliseconds will all be
zero, which effectively means
* midnight on the date (year, month, and day) in question.</p>
*
* @param date a date given in DD-Mon-YYYY format, e.g.
01-May-2006.
* @return java.sql.Date expressed with a default time of midnight.
*/
static public java.sql.Date toSqlDate(String date) {
java.text.SimpleDateFormat sdf = new
java.text.SimpleDateFormat("dd-MMM-yyyy");
sdf.setLenient(false);
java.util.Date utilDate = null;
try {
utilDate = sdf.parse(date);
} catch (ParseException p_excp) {
throw new IllegalArgumentException("Encountered
ParseException at offset " + p_excp.getErrorOffset() + " while
attempting to convert the String " + date + " to a java.sql.Date.
Details: " + p_excp.getMessage());
}
java.sql.Date sqlDate = new java.sql.Date(utilDate.getTime());
return (sqlDate);
}
--
Rhino
.
- References:
- Date question
- From: hoho123
- Date question
- Prev by Date: Re: Merge strategy
- Next by Date: Tomcat Newbie, need help with caching
- Previous by thread: Re: Date question
- Next by thread: Tomcat Newbie, need help with caching
- Index(es):
Relevant Pages
|