How change format time from jSpinner?

梦想的初衷 提交于 2019-12-24 14:14:35

问题


I use a jSpinner to choose and save time.

I want enter the start time for a task in the database. But the format that saves the database is this: Tue Apr 15 17:24:56 BST 2014

I want in HH:mm.

This is the code I use to write the data in the database:

    public void UpdateTask() {
    try {
        Task t1 = new Task();
        t1.setIdTask(jTIdTask.getText());
        t1.setDate(jTDate.getText());

        ---->  t1.setHourBegin(jSpinner2.getValue().toString());  // This is what I need change

        TaskDao dao = new TaskDao();
        dao.updateTask(t1);

    } catch (SQLException ex) {
        Logger.getLogger(jTTask.class.getName()).log(Level.SEVERE, null, ex);
    }
}

CLASS DAO

  public void updateTask(Taskst1) throws SQLException{
    String sql = "update Taskset idTask=?, date=?, hourBegin=? where idTask=?"; 
    PreparedStatement stmt = this.conexao.prepareStatement(sql);
    stmt.setString(1, st1.getIdTask());
    stmt.setString(2, st1.getDate());
    stmt.setString(3, st1.getHourBegin());
    stmt.setString(4, st1.getIdTask());

    stmt.execute();
    stmt.close();
    conexao.close();
}

FORM


SOLUTION

   public void UpdateTask() {
    try {
        SimpleDateFormat sdf = new SimpleDateFormat("HH:mm");
        Task t1 = new Task();
        t1.setIdTask(jTIdTask.getText());
        t1.setDate(jTDate.getText());

        String time = sdf.format(jSpinner2.getValue());
        t1.setHourBegin(time);

        TaskDao dao = new TaskDao();
        dao.updateTask(t1);

    } catch (SQLException ex) {
        Logger.getLogger(jTTask.class.getName()).log(Level.SEVERE, null, ex);
    }
}

回答1:


jSpinner2.getValue().toString() is basically asking the returned object for whatever String representation it has, in this instance, you're asking a Date object to pass you back it's default String representation.

Remember, Date does not have any concept of a format, it's just a container for the number of milliseconds since the Unix epoch.

You will need to use a DateFormatter of some kind to format the Date value from the JSpinner to the format you want...

A better solution would be to use some kind of date/time data type in you database...

Updated

The stored in the JSpinner is a Date object, it has no concept of a format. You will need to use some kind of DateFormatter to take to from been a Date to been a String value formatted the way you want.

Object value = jSpinner2.getValue();
if (value instanceof Date) {
    String time = new SimpleDateFormat("HH:mm").format(value);
    t1.setHourBegin(time);
} else {
    // Deal with the invalid value...
}


来源:https://stackoverflow.com/questions/23103328/how-change-format-time-from-jspinner

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!