Please let me know how to get day, month and year in JSP from mysql Date.

Dani AI

Generated

asked how to get day, month and year from a MySQL DATE in JSP. pointed at formatting and steered toward retrieving the date from JDBC. The short, practical guidance: get the date out of the ResultSet, convert to a date-only object, then read the components. Below are clear, safe ways to do that and a few common pitfalls to watch for.

Java 8+ (preferred)

LocalDate d = rs.getObject("my_date", java.time.LocalDate.class);
int day = d.getDayOfMonth();
int month = d.getMonthValue();
int year = d.getYear();

Fallback (JDBC before getObject/LocalDate support)

java.sql.Date sqlDate = rs.getDate("my_date");
java.time.LocalDate d = sqlDate.toLocalDate();
int day = d.getDayOfMonth();
int month = d.getMonthValue();
int year = d.getYear();

Pre-Java 8 approach (if you must)

java.sql.Date sqlDate = rs.getDate("my_date");
Calendar cal = Calendar.getInstance();
cal.setTime(sqlDate);
int day = cal.get(Calendar.DAY_OF_MONTH);
int month = cal.get(Calendar.MONTH) + 1;  // Calendar.MONTH is zero-based
int year = cal.get(Calendar.YEAR);

JSP display option: use JSTL <fmt:formatDate> to avoid scriptlets, e.g. pattern="dd" / pattern="MMMM" / pattern="yyyy".

Notes and gotchas

  • Java date-format tokens differ from what posted: use d/dd for day of month, E/EEE/EEEE for weekday names, M/MM/MMM/MMMM for month, and y/yy/yyyy for year.
  • Prefer java.time and DateTimeFormatter (thread-safe) over SimpleDateFormat. See the Java docs for LocalDate and java.sql.Date for details: LocalDate and java.sql.Date.
  • If you only need parts, you can get them in SQL: SELECT DAY(col), MONTH(col), YEAR(col) FROM ....

Recommended Answers

All 2 Replies

you can use the format on the Date

Like
dd = 12
ddd = sun
dddd = sunday

and the same for the month and year

Ever tried the getDate() method of ResultSet, It would give you a java.sql.Date object from the date in your MySQL table.
Extracting Month,Year and Day from it should be trivial then.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.