【问题标题】:Returning only time using SpinnerDateModel使用 SpinnerDateModel 仅返回时间
【发布时间】:2014-08-03 06:12:01
【问题描述】:

我目前正在使用带有 JSpinner 的 SpinnerDateModel 在我的 java swing 应用程序中设置时间。以下是我的代码:

shiftTime = new JSpinner(new SpinnerDateModel());
    JSpinner.DateEditor de_shiftTime = new JSpinner.DateEditor(shiftTime,
            "HH:mm:ss");
    shiftTime.setEditor(de_shiftTime);
    //shiftTime.setValue(new Date()); // will only show the current time
    shiftTime.setSize(108, 22);
    shiftTime.setLocation(436, 478);
    add(shiftTime);

但是,当我使用 .getValue() 方法将此选定时间添加到我的数据库中时(我使用的是 mySql),时间与日期一起添加。我不想要日期,只想要时间,例如13:59:16。 但是,我现在得到的是“Thu Jan 01 13:59:16 SGT 1970”。

有没有办法覆盖新的 SpinnerDateModel() 或删除结果中的日期?任何帮助是极大的赞赏!谢谢! :-)

【问题讨论】:

  • 假设数据库字段为TimeStamp,为什么不根据JSpinner返回的值创建一个java.sql.TimeStamp呢?
  • 我目前正在使用 varchar 将时间存储在我的数据库中!不过还是谢谢 :-)

标签: java swing jspinner


【解决方案1】:

您可以使用SimpleDateFormat 将其转换为所需的输出:

Date date=(Date)shiftTime.getValue();
SimpleDateFormat format=new SimpleDateFormat("HH:mm:ss");
System.out.println(format.format(date));

JSpinner.getValue 返回 Object 并且您只是打印默认返回的值 Date#toString()

【讨论】:

    【解决方案2】:

    如果你使用joda-time——你应该是因为java日期库被严重破坏了,你的代码看起来像:

    DateTime date = new DateTime((Date)shiftTime.getValue());
    ISODateTimeFormatter fmt = ISODateTimeFormatter.timeNoMillis();
    String dateAsString = fmt.print(date);
    System.err.println(dateAsString);
    

    如果您需要进一步的帮助,请发表评论。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-10-23
      • 2016-12-21
      • 2018-09-07
      • 1970-01-01
      相关资源
      最近更新 更多