【问题标题】:Java How to get just HH:mm:ss from DateJava 如何从日期中获取 HH:mm:ss
【发布时间】:2014-10-13 13:52:43
【问题描述】:

对于我的第一个 Java 应用程序,我正在制作秒表。秒表将过去的时间显示为小时、分钟和秒。像这样 00:00:00。

我希望在一定时间(用户定义)过去后显示警报(警报框,等等)。

这是生成秒表显示的代码(忽略十进制,我们不会关心警报):

    swChronometer = new Timer(10, new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            int decisec = (int)(System.currentTimeMillis() - swWatchStart) / 10; // 10 x millisecond
            int seconds = decisec / 100;
            int days = seconds / 86400; // 86400 seconds in a day
            int hours = (seconds / 3600) - (days * 24); // 3600 seconds in a hour
            int min = (seconds / 60) - (days * 1440) - (hours * 60); // 60 seconds in a min
            int sec = seconds % 60;
            int decis = decisec % 100;

            //------------------------------------------------------- format the ints
            DecimalFormat formatter = new DecimalFormat("00");
            String hoursFormatted = formatter.format(hours);
            String minFormatted = formatter.format(min);
            String secFormatted = formatter.format(sec);
            String decisFormatted = formatter.format(decis);

            //------------------------------------------------------- update display
            String s = new String(""+hoursFormatted+":"+minFormatted+":"+secFormatted+"");
            String sDs = new String(decisFormatted);
            swDisplayTimeLabel.setText(s);
            swDisplayDeciseconds.setText(sDs);
        }        
    });

如您所见,Timer 整数最终会转换为字符串然后显示。

After 和 Every 都有单选按钮 - 因此在 n 时间或每 n 时间后发出警报。

我有一个 JSpinner,因此用户可以定义 n 时间,该时间被格式化为仅显示 00:00:00:

    // ----------------------------------
    // set spinner format
    // ----------------------------------
    // inital date at 12pm 00:00:00
    Calendar calendar = Calendar.getInstance();
    calendar.set(Calendar.HOUR_OF_DAY, 24); // 24 == 12 PM == 00:00:00
    calendar.set(Calendar.MINUTE, 0);
    calendar.set(Calendar.SECOND, 0);

    swSpinnerTime.setValue(calendar.getTime());

    // format field
    JSpinner.DateEditor editor = new JSpinner.DateEditor(swSpinnerTime, "HH : mm : ss");           
    DateFormatter formatter = (DateFormatter)editor.getTextField().getFormatter();
    formatter.setAllowsInvalid(false); // sets it so user cant edit colon
    formatter.setOverwriteMode(true);

    swSpinnerTime.setEditor(editor);

还有一个组合框,用户可以选择什么类型的警报。

每当用户对这些输入中的任何一个进行操作时,都会调用我的函数来处理它:

private void swAlarmSettings() {
    //------------------------------------------------------- which radio is selected
    String swRadioText = "";

    if(swRadioAfter.isSelected()) {
        swRadioText = swRadioAfter.getText();
    }

    if(swRadioEvery.isSelected()) {
        swRadioText = swRadioEvery.getText();
    }

    // debug
    System.out.println("Radio Selected: " +swRadioText);

    //------------------------------------------------------- which time is selected     
    Date swSpinnerTimeValue;  
    swSpinnerTimeValue = (Date)swSpinnerTime.getValue();

    // debug
    System.out.println("swSpinnerTimeValue: " +swSpinnerTimeValue);

    //------------------------------------------------------- which alarm is selected
    String swDropDownSelected = (String)swDropDown.getSelectedItem();

    // debug
    System.out.println("swDropDownSelected: " +swDropDownSelected);       
}

但是,无论何时调用此函数,它都会将日期打印为:

   swSpinnerTimeValue: Tue Oct 14 00:00:00 BST 2014

所以这就是我坚持如何进行的地方。当我已经在 J​​Spinner 中格式化它时,我没想到会显示整个日期(即使它是错误的(今天是 10 月 13 日,而不是 14 日))。

所以我假设我需要以某种方式解析这个值,去掉我不需要的数据,所以我只剩下 HH:mm:ss 然后将其转换为字符串,以便我可以比较它到我的秒表显示(字符串 swDisplayTimeLabel),然后在它们匹配时发出警报。

我希望我的查询已明确并提供了足够的信息。感谢您的帮助。

我在 Netbeans 中工作并使用 Swing 设计部分来创建我的应用程序。

【问题讨论】:

    标签: java string parsing date format


    【解决方案1】:

    Java Date 是即时的,不会保留您预期的输出格式。为此,您需要使用DateFormat。例如,

    System.out.println("swSpinnerTimeValue: " + new SimpleDateFormat("HH:mm:ss")
        .format(swSpinnerTimeValue));
    

    【讨论】:

      【解决方案2】:

      tl;博士

      问题和其他答案使用麻烦的旧日期时间类,现在是遗留的,被 java.time 类取代。

      Duration.between( 
          instantThen ,
          Instant.now().truncatedTo( ChronoUnit.SECONDS )
      )
      

      ……和……

      String.format( 
          "%02d:%02d:%02d", 
          duration.toHoursPart() , 
          duration.toMinutesPart() , 
          duration.toSecondsPart() 
      )
      

      使用 java.time

      Instant 类表示UTC 中时间轴上的时刻,分辨率为nanoseconds(最多九 (9) 位小数)。

      Instant instant = Instant.now() ;
      

      你似乎只关心整秒钟。所以我们可以去掉任何小数秒。

      Instant instant = Instant.now().truncatedTo( ChronoUnit.SECONDS ) ;
      

      要以小时-分钟-秒的粒度表示与时间轴无关的时间跨度,请使用 Duration 类。

      Duration duration = Duration.between( then , instant ) ;
      

      您可以生成一个字符串,以标准 ISO 8601 格式的文本 PTxHxMxS 表示该时间跨度,其中 P 标志着开始,T 将任何年-月-日与我们的小时-分钟-秒分开.所以一个半小时是PT1H30M

      String output = duration.toString();
      

      要获得时钟样式的显示,请创建自己的字符串。要获取每个部分、小时、分钟和秒,您必须自己进行数学运算,类似于 Java 8 中的问题。在 Java 9 及更高版本中,您可以调用 the to…Part methods

      int hours = duration.toHoursPart() ;
      int minutes = duration.toMinutesPart() ;
      int seconds = duration.toSeconds() ;
      
      String output = String.format("%02d:%02d:%02d", hours , minutes , seconds ) ;
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-11-30
        • 2013-12-08
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多