-2

when i make something like this in my servlet im still getting date format like Sun Jun 07 00:59:46 CEST 2020 but i want to make it like 2020.06.07

Code in my servlet :

SimpleDateFormat sdfo = new SimpleDateFormat("yyyy-MM-dd");
Date currentDate = new Date();
sdfo.format(currentDate);
request.setAttribute("currentDate", currentDate);

And my jsp file :

Current date: <c:out value="${currentDate}"/>

What i should change here?

BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
Pabblo96
  • 29
  • 6

1 Answers1

2

You have set the currentDate instead of the formatted date string into request.

Replace

sdfo.format(currentDate);
request.setAttribute("currentDate", currentDate);

with

String today = sdfo.format(currentDate);
request.setAttribute("currentDate", today);

I also recommend you use java.time.LocalDate and DateTimeFormatter.ofPattern instead of using the outdated java.util.Date and SimpleDateFormat as shown below:

DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
LocalDate currentDate = LocalDate.now();
String today = currentDate.format(formatter);
request.setAttribute("currentDate", today);

Check this to learn more about the modern date/time API.

Arvind Kumar Avinash
  • 71,965
  • 6
  • 74
  • 110