Error formatting date:

Asked

Viewed 300 times

2

Hello, I’m formatting the date with the following code:

Date data = null;

    SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    try {

      data = format.parse(request.getParameter("txtdata"));

    } catch (Exception e) {

        JOptionPane.showMessageDialog(null,"Erro ao formatar data: " +e.getMessage());

    }
    event.setEventodata(data);

By clicking register, in the form below:

inserir a descrição da imagem aqui

The following error appears:

inserir a descrição da imagem aqui

I’m saving this in the bank ok? The attribute type is: datetime not null; There’s something wrong with the conversion?

  • What value request.getParameter("txtdata") returns? Tries to use a System.out.println to be sure

  • Format is wrong. Change to new SimpleDateFormat("dd-MM-yyyy HH:mm:ss")

  • I already changed the format, it didn’t work, because anyway I have to take yyyy-MM-dd, since I’m saving in the "Database".

  • But I just put a Joptionpane.showMessageDialog(null,"-" +data); to return the date and is coming "null", and when giving the error returns the date in the error, I don’t understand it now :s The request.getParameter is correct.

2 answers

2

Good afternoon friend, please post your Model Class.

Here is an example of formatting with Simpledateformat....

SimpleDateFormat fmt = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");
Date data = fmt.parse("17/12/2007 19:30:20"); 
String str = fmt.format(data); 

1

By error message we may have a clue of the problem:

Unparseable date: "2016-07-28T21:58:58"

Note that enter the date (2016-07-28) and the time (21:58:58) there’s a letter T. This letter is the separator between date and time, according to the format defined by ISO 8601 (and that seems to be the format in which the parameter is being sent).

The SimpleDateFormat gave error because you are using a space between date (yyyy-MM-dd) and the time (HH:mm:ss). To correct, just change the space by the letter T.

One detail is that it should be in simple quotes ('T'), so that the SimpleDateFormat understand that it is the letter T itself (otherwise he will try to interpret it as a letter with special meaning, such as y meaning "year", for example).

Then it would look like this:

SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");

With that, the parse will be done correctly.

Browser other questions tagged

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