How to convert Time type to String?

Asked

Viewed 1,240 times

0

I have a field horaConsulta and I can’t turn him into String

DAO

stmt.setTime(4, new java.sql.Time(consulta.getHoraConsulta().getTime()));

Servlet

Time horaConsulta = converterTime(request.getParameter("horaConsulta").replace(":", ":"));

  • Post the code of converterTime to make it clearer.

  • Why the replace(":",":")? You want your own Time in String? The .toString() does not serve?

1 answer

4

If I understood your question is to turn Dates and Times into and vice versa Strings, an easy way to do it is by using Simpledateformat, passing a string with hour format. The reverse is also possible.

Example

DateFormat formatter = new SimpleDateFormat("HH:mm:ss"); //Hora, minuto, segundo.
formatter.format(new Date()); // Deverá mostrar hora atual em string
DateFormat parser = new SimpleDateFormat("DD/mm/YYYY HH:mm:ss");
Date date = parser.parse("21/02/1987 02:02:00"); // Deverá transformar a string em Date se a data estiver no padrão

How to Convert Data to String and Date Again

Documentation of the Simpledateformat Class

Documentation of the Dateformat Class

  • His object is a Time, not a Date.

  • 1

    I saw that I had . getHoraConsult(). getTime(), I suspected it was using Date(the old API) in java. The date getTime() will return a long, can be used in the java.sql.Time constructor, which according to javadoc, is a thin wrapper used by the jdbc api, for SQL TIME values in milliseconds. So it’s natural to use Object as Date, then turn it into Time.

  • Hmmm truth. Good observation.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.