I can retrieve the complete date of all the records but I only want to retrieve the day of each record. For example I have a date 2017-01-20, but I only want to retrieve 20. How do I do that? Here is my code:
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
String date = sdf.format(calendar.getDate());
String sql = "SELECT reserve_date FROM reservation";
try
{
pst = conn.prepareStatement(sql);
rs = pst.executeQuery();
text.setText("");
while(rs.next()){
String str = rs.getString("reserve_date");
text.append(str);
text.append("\n");
}
pst.close();
rs.close();
}
catch(Exception e)
{
JOptionPane.showMessageDialog(null, e);
}
finally{
try{
rs.close();
pst.close();
}catch(Exception e){JOptionPane.showMessageDialog(null, e);}
}
You could use the MySQL function DAYOFMONTH
like
String sql = "SELECT DAYOFMONTH(reserve_date) FROM reservation";
And then either
String str = rs.getString(1);
or
int dayOfMonth = rs.getInt(1);
myResultSet.getObject( reserve_date , LocalDate.class ) // Retrieve `LocalDate` object from database.
.getDayOfMonth() // Extract an integer for day-of-month number.
The Answer by Frisch is correct. Another route is through the java.time library.
Fetch from the database using objects, specifically a java.time.LocalDate
object. The interrogate for the day-of-month.
LocalDate ld = myResultSet.getObject( reserve_date , LocalDate.class ) ;
int dayOfMonth = ld.getDayOfMonth() ;
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.