代码之家  ›  专栏  ›  技术社区  ›  user3763216

如何从字符串中设置JSpinner的值?

  •  1
  • user3763216  · 技术社区  · 12 年前

    我目前正在使用JSpinner设置一个时间值,然后将其作为varchar更新到我的数据库中,例如12:00:00 am。但是,在另一种形式中,我希望将添加到数据库中的时间检索到我的更新表单中的JSpinner中。更新表单用于用户更新他们之前选择的时间(例如,如上所述的12:00:00上午)。现在,默认时间值是当前时间。我尝试使用.setValue()方法,但它是一个非法值,因为我检索的时间是一个字符串。以下是我的代码,让事情更清楚:

    shiftTime = new JSpinner(new SpinnerDateModel());
        JSpinner.DateEditor de_shiftTime = new JSpinner.DateEditor(shiftTime,
                "hh:mm:ss a");
        shiftTime.setEditor(de_shiftTime);
        shiftTime.setSize(108, 22);
        shiftTime.setLocation(436, 478);
        add(shiftTime);
        shiftTime.setValue(a.getVolDutyShift());
    

    .getVolDutyShift()方法返回字符串(12:00:00 AM,字符串格式) a是调用.getVolDutyShift()方法的对象。 我应该如何解析这个.getVolDutyShift(),以便JSpinner将时间加载为数据库中的时间(12:00:00 AM)?

    2 回复  |  直到 12 年前
        1
  •  1
  •   Niru    12 年前

    试试看。它将把字符串中的时间转换为java.sql.time。

        SimpleDateFormat format = new SimpleDateFormat("HH:mm:ss a");
        java.util.Date d =(java.util.Date)format.parse(a.getVolDutyShift());
        java.sql.Time time = new java.sql.Time(d.getTime());
        shiftTime.setValue(time );
    

    但您应该始终将日期和时间保存在数据库中的原始数据类型中,而不是保存为varchar

        2
  •  0
  •   Kossmare    9 年前

    我总是在解析方面遇到问题。我找到了另一种方法,不用解析就能解决你的问题。。。

    JSpinner.DateEditor de = new JSpinner.DateEditor(shiftTime, a.getVolDutyShift());
    jSpinner1.setEditor(de);