I am reading a date column from the Oracle DB.
The column type is Date.
Example Date data is: 2011-12-06 14:28:12
Now when I am reading this date I want to split the date part into a separate String and Time part into another.
// here’s the code I am working with.
DateFormat df = new SimpleDateFormat("yyyy-MM-DD HH:mm:ss");
// some loop.
SomeBean bean = new SomeBean();
Date date = convertTimestamp(rs.getTimestamp("DATE_VAL"));
bean.setTime(date==null?"":convertToTimeStamp(date,true));
bean.setDate(date==null?"": df.format(date));
// end some loop.
private java.util.Date convertTimestamp(java.sql.Timestamp timestamp) {
if (timestamp == null)
return null;
else
return new java.util.Date(timestamp.getTime());
}
private String convertToTimeStamp(Date date, boolean showSeconds) {
Calendar c = Calendar.getInstance();
c.setTime(date);
return convertToTimeStamp(c, showSeconds);
}
public static String convertToTimeStamp(Calendar time, boolean showSeconds) {
String hours = Integer.toString(time.get(Calendar.HOUR_OF_DAY));
if (hours.length() == 1) {
hours = '0' + hours;
}
String minutes = Integer.toString(time.get(Calendar.MINUTE));
if (minutes.length() == 1) {
minutes = '0' + minutes;
}
if (showSeconds) {
String seconds = Integer.toString(time.get(Calendar.SECOND));
if (seconds.length() == 1) {
seconds = '0' + seconds;
}
return hours + ":" + minutes + ":" + seconds;
} else {
return hours + ":" + minutes;
}
}
Please help. Your help will be appreciated.
Thanks
first of all I would recommend to have a look at Joda-Time: it has a lot of easy going date and time functions. (a lot easier than the java date).
converting java.sql.Date to joda DateTime I use:
This will at least save you one function, and will maybe help you to your solution.
To convert a java.sql.TimeStamp to joda DateTime:
Second of all, why not use the DateFormatter to convert your date to a string you want?
Sticking to the Joda DateTime, use:
U can use the same formats as the java.Date and Time formatters:
pattern = “DD-MM-YYYY” (dutch notation) or “YYYY-MM-DD” (uk notation) and for time pattern=”hh:mm:ss”
if you want to stick to your method, create another SimpleDateFormat, and use this last pattern (“hh:mm:ss”) to create a time String.
Please, at leaste change this function:
in to:
In your last remark, i gues you asked for: