2

我正在进行一个以 hh:mm 为单位捕获间隔时间的项目。我有 2 个名为 btnTimeOut 和 btnTimeIn 的按钮,它们都在单击时捕获系统时间。要求是在 hh:mm 等 12:30 - 10:00 = 02:30 (hh:mm) 中获取 btnTimeOut 和 btnTime 之间的间隔。

目前我使用以下代码作为间隔,但它以分钟等形式返回。12:30 - 10:00 = 150 分钟。

  String timeOut = lblTimeOut.getText();
  String timeIn = lblTimeIn2.getText();

  SimpleDateFormat format = new SimpleDateFormat("hh:mm");

  Date d1 = null;
  Date d2 = null;

  try {
      d1 = format.parse(timeOut);
      d2 = format.parse(timeIn);
  } 
  catch (Exception e){
      e.printStackTrace();
  }

  long diff = d2.getTime() - d1.getTime();
  long diffMinutes = diff / (60 * 1000);         
  long diffHours = diff / (60 * 60 * 1000);  

  lblSurface.setText(String.valueOf(diffMinutes)); 

如何获取表单中的持续时间hh:mm

我使用了 Joda 时间并以无效格式返回:“12:19”在“:19”处格式错误。至于我的其他触发显示时间的按钮。

DateFormat timeFormat = new SimpleDateFormat("hh:mm");
Date date = new Date();  
String time = timeFormat.format(date);  
lblTimeIn2.setText(time);

Timer timer = new Timer(1000, timerListener);  
    // to make sure it doesn't wait one second at the start  
timer.setInitialDelay(0);  
timer.start();   
}         

我不知道出了什么问题,我是否也需要使用 joda time 来显示其他标签的时间?

4

3 回答 3

3

我个人会使用JodaTime,因为它考虑到了天数之间的差异(即 23:30-02:30 之间的差异)并且有很好的内置格式化程序

public class TestJodaTime {

    public static void main(String[] args) {

        DateTime start = new DateTime(2012, 11, 11, 23, 30, 0, 0);
        DateTime end = new DateTime(2012, 11, 12, 1, 30, 0, 0);
        Interval interval = new Interval(start, end);
        Period toPeriod = interval.toPeriod();

        PeriodFormatter dateFormat = new PeriodFormatterBuilder()
                        .printZeroAlways().minimumPrintedDigits(2)
            .appendHours().minimumPrintedDigits(2)
            .appendSeparator(":")
            .appendMinutes().minimumPrintedDigits(2)
            .toFormatter();        
        System.out.println(toPeriod.toString(dateFormat));
    }
}

哪个会输出02:00

扩展示例

在此处输入图像描述

public class TestJodaTime {

    public static void main(String[] args) {
        new TestJodaTime();
    }

    public TestJodaTime() {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                } catch (ClassNotFoundException ex) {
                } catch (InstantiationException ex) {
                } catch (IllegalAccessException ex) {
                } catch (UnsupportedLookAndFeelException ex) {
                }

                JFrame frame = new JFrame("Test");
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.setLayout(new BorderLayout());
                frame.add(new JodaPane());
                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            }

        });
    }

    public class JodaPane extends JPanel {

        private JTextField startHour;
        private JTextField startMin;
        private JTextField endHour;
        private JTextField endMin;
        private JButton diffButton;
        private JLabel lblDiff;
        private JButton markStart;
        private JButton markEnd;
        private Timer timer;
        private JLabel realTime;

        public JodaPane() {

            markStart = new JButton("Mark");
            markEnd = new JButton("Mark");

            startHour = new JTextField(2);
            startMin = new JTextField(2);
            endHour = new JTextField(2);
            endMin = new JTextField(2);
            diffButton = new JButton("=");
            lblDiff = new JLabel("00:00");
            realTime = new JLabel("00:00.00");

            setLayout(new GridBagLayout());
            GridBagConstraints gbc = new GridBagConstraints();
            gbc.gridx = 0;
            gbc.gridy = 0;
            gbc.anchor = GridBagConstraints.WEST;
            add(new JLabel("From"), gbc);
            gbc.gridx++;
            add(startHour, gbc);
            gbc.gridx++;
            add(new JLabel(":"), gbc);
            gbc.gridx++;
            add(startMin, gbc);
            gbc.gridx++;
            add(markStart, gbc);
            gbc.gridx++;
            add(new JLabel(" to "), gbc);
            gbc.gridx++;
            add(endHour, gbc);
            gbc.gridx++;
            add(new JLabel(":"), gbc);
            gbc.gridx++;
            add(endMin, gbc);
            gbc.gridx++;
            add(markEnd, gbc);
            gbc.gridx++;
            add(diffButton, gbc);
            gbc.gridx++;
            add(lblDiff, gbc);

            gbc.gridy++;
            add(realTime, gbc);

            diffButton.addActionListener(new ActionListener() {
                public boolean isValid(JTextField field) {
                    return field.getText() != null && field.getText().length() > 0;
                }
                @Override
                public void actionPerformed(ActionEvent ae) {
                    if (isValid(startHour) && isValid(startMin)
                                    && isValid(endHour) && isValid(endMin)) {
                        int hourStart = Integer.parseInt(startHour.getText());
                        int minStart = Integer.parseInt(startMin.getText());
                        int hourEnd = Integer.parseInt(endHour.getText());
                        int minEnd = Integer.parseInt(endMin.getText());

                        String prefix = "";
                        if (hourEnd < hourStart) {
                            int tmp = hourStart;
                            hourStart = hourEnd;
                            hourEnd = tmp;
                            prefix = "-";
                        }

                        System.out.println("Start = " + hourStart + ":" + minStart);
                        System.out.println("End = " + hourEnd + ":" + minEnd);

                        DateTime start = new DateTime(0, 1, 1, hourStart, minStart, 0, 0);
                        DateTime end = new DateTime(0, 1, 1, hourEnd, minEnd, 0, 0);
                        Interval interval = new Interval(start, end);
                        Period toPeriod = interval.toPeriod();

                        PeriodFormatter dateFormat = new PeriodFormatterBuilder()
                                        .printZeroAlways().minimumPrintedDigits(2)
                                        .appendHours().minimumPrintedDigits(2)
                                        .appendSeparator(":")
                                        .appendMinutes().minimumPrintedDigits(2)
                                        .toFormatter();
                        lblDiff.setText(prefix + dateFormat.print(toPeriod));
                    }
                }

            });

            markStart.addActionListener(new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent ae) {
                    Calendar cal = Calendar.getInstance();
                    startHour.setText(Integer.toString(cal.get(Calendar.HOUR_OF_DAY)));
                    startMin.setText(Integer.toString(cal.get(Calendar.MINUTE)));
                    diffButton.doClick();
                }

            });
            markEnd.addActionListener(new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent ae) {
                    Calendar cal = Calendar.getInstance();
                    endHour.setText(Integer.toString(cal.get(Calendar.HOUR_OF_DAY)));
                    endMin.setText(Integer.toString(cal.get(Calendar.MINUTE)));
                    diffButton.doClick();
                }

            });

            timer = new Timer(500, new ActionListener() {
                private SimpleDateFormat sdf = new SimpleDateFormat("HH:mm.ss");
                @Override
                public void actionPerformed(ActionEvent ae) {
                    realTime.setText(sdf.format(new Date()));
                }
            });
            timer.setRepeats(true);
            timer.setCoalesce(true);
            timer.start();


        }

    }

}

你的问题有点模糊,所以我做了一个广泛的例子。马克,基本上自动用当前时间填充字段。

几乎没有验证;)

于 2012-11-11T06:56:17.740 回答
2

当你得到分钟时,它也包括小时。只需将分钟除以60得到小时,然后用除法的余数更新分钟,如下所示。

    long diffMinutes = diff / (60 * 1000);  //difference in minutes       
    long diffHours = (long) diffMinutes/60; //get hours from diff minutes
    diffMinutes  = diffMinutes % 60; //remainder of minutes after converting hours

最后在文本中设置小时和分钟:

     lblSurface.setText(diffHours + ":" + diffMinutes);

由于":"附加在两者之间,由于隐式转换应该没问题。

于 2012-11-11T05:49:28.837 回答
2
String.format("%1d:%2d", mins/60, (mins%60))

例如

public class HoursMinutesFormat {

    public static void main(String[] args) {
        int mins = 150;
        System.out.println(String.format("%1d:%2d", mins/60, (mins%60)));
    }
}

输出

2:30
于 2012-11-11T05:57:26.013 回答