Fetching SQL datetime from Database is returned in different format
843859Nov 6 2008 — edited Nov 20 2014Hi All,
I have a datetime column which stores a date in this format: yyyy/MM/dd hh:mm:ss a - where 'a' is the AM/PM identifier.
Therefore a date in this column could be represented as: 2008/10/16 08:53:12 AM. (This is a value that I copied directly from the database i.e. this is the exact format that is used in the database)
The problem is when I retrieve this datetime from the database I can't seem to get the exact format as it is above. Here is what I have tried:
1. ResultSet.getString() - returns: 2008-10-16 08:53:12.000
2. ResultSet.getDate() - returns: 2008-10-16
3. ResultSet.getTime() - returns: 08:53:12
4. ResultSet.getTimestamp() - returns: 2008-10-16 08:53:12.0
I have also tried converting each of the dates above into the format required using Calendar and SimpleDateFormat, like so:
SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd hh:mm:ss a");
Calendar cal = Calendar.getInstance();
sdf.setLenient(true);
String dateFormat = "";
String dateFromDB = "2008-10-16 08:53:12.0"; // Replace this with any of the above dates
try {
java.util.Date parsedDate = sdf.parse(dateFromDB); // Fails at this line
cal.setTime(parsedDate);
dateFormat = sdf.format(cal.getTime());
System.out.println("Date in correct format: " + dateFormat);
} catch (ParseException pe) {
System.out.println("ParseException caught!");
System.out.println("Reason: " + pe.getMessage());
}//End try...catch
I have tried googling but have not found anything explaining how to retrieve a datetime value in the same format that it is in, in the database.
I would greatly appreciate any help in this.
Many thanks,
javaTheHutt