Formatting Data with SimpleDateFormat

3

My problem is this:

I have JTable with several populated columns with data pulled from my database. Some of these columns are time values, for example, 0834 is pulled from the database and I would like it to be displayed 08:34

I'm not able to implement library resources SimpleDateFormat . I followed some tutorials from American StackOverflow and my output is always the same: 21:00 , regardless of the value the bank sends.

My code in class TimestampCellRenderer is

import java.text.SimpleDateFormat;
import javax.swing.table.DefaultTableCellRenderer;

public class TimestampCellRenderer extends DefaultTableCellRenderer {

    SimpleDateFormat formatter = new SimpleDateFormat("HH:mm");

    public TimestampCellRenderer() {
        super();
    }

    public void setValue(Object value) {
        setText((value == null) ? "" : formatter.format(value));
    }
}

And in the GUI class I have the following line:

tableResultados.getColumnModel().getColumn(4).setCellRenderer(new TimestampCellRenderer());
    
asked by anonymous 17.11.2016 / 03:40

1 answer

0

The problem is that you are using the format that works with a Date, when you should initially work with parse since your date is persisted as an integer value. To work with SimpleDateFormat you would need to use the parse and format methods together. One way to do this would be:

//Esse valor viria do banco nesse formato.
Integer hora = 834;
SimpleDateFormat formatter = new SimpleDateFormat("HH:mm");

String horaParaFormatar = String.format("%04d", hora);
Date parsedDate = formatter.parse(String.join(":", 
    horaParaFormatar.substring(0, 2), horaParaFormatar.substring(2, 4)));
System.out.println(formatter.format(parsedDate));

Note that to use parse you would need to add the hour and minute separator to fit the formatter pattern. A more elegant way of solving the problem would be to modify the format of the value stored in the database to bigint so that it stores the long value representing the date. So you could keep your call to the format just by passing that long value, which would be converted to the time of the represented Date.

    
21.11.2016 / 16:36