12:xx 在 SimpleDateFormat.format("hh:mm:ss") 中显示为 00:xx

12:xx shown as 00:xx in SimpleDateFormat.format("hh:mm:ss")

在以下代码中使用 SimpleDateFormatter.format 时,12:00 和 12:59 之间的小时数在 startDateText TextView 中显示为 00:00 到 00:59,而自13:00 它们正确显示为 13:xx、14:xx 到 23:59。

---- 根据要求重构代码 当 dtold.parse(...) 中的字符串是示例中的输出小时数是 00:00,当它是“13:00”时它是正确的“13:00”

import java.text.SimpleDateFormat;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.util.Calendar;
import java.util.Date;
import java.util.TimeZone;


// one class needs to have a main() method
public class HelloWorld
{
  // arguments are passed using the text field below this editor
  public static void main(String[] args)
  {
        SimpleDateFormat dtnew = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");
        SimpleDateFormat dtold = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");

            try {

            Calendar cal = Calendar.getInstance();
            cal.setTime(dtold.parse("2017-03-12 12:33:33"));
            cal.add(Calendar.SECOND, 10);
            System.out.println(dtnew.format(cal.getTime()));

        } catch (Exception e) {

            throw new RuntimeException(e);
        }


  }
}

首先是几个像您一样的格式化程序,仅使用 java.time 中的 DateTimeFormatter,现代 Java 日期和时间 API:

private static DateTimeFormatter dtfOld = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
private static DateTimeFormatter dtfNew = DateTimeFormatter.ofPattern("dd-MM-yyyy HH:mm:ss");

有两点需要注意:(1) 按照逻辑顺序声明格式化程序,即您要使用它们的顺序。在问题中使用相反的顺序让我感到困惑,我不确定它是否也让你感到困惑。 (2) 在 dtfOld 中,使用大写 HH 表示从 00 到 23 之间的一天中的小时。小写 hh 表示从 01 到 12 的 AM 或 PM 中的小时(在这种情况下相同格式模式字母适用于 SimpleDateFormatDateTimeFormatter;但存在差异)。现在剩下的很无聊,只比你的代码简单:

    LocalDateTime parsed = LocalDateTime.parse("2017-03-12 12:33:33", dtfOld);
    System.out.println(parsed);
    LocalDateTime dateTime = parsed.plusSeconds(10);
    System.out.println(dateTime);
    System.out.println(dateTime.format(dtfNew));

输出为:

2017-03-12T12:33:33
2017-03-12T12:33:43
12-03-2017 12:33:43

我推荐java.time。您使用的旧日期和时间 classes — SimpleDateFormatCalendarDate — 早已过时。现代 classes 不仅在这种情况下允许更简单的代码,而且很常见。我发现 java.time 通常更好用。

你的代码出了什么问题?

我已经给出了提示:小写字母 hh 表示上午或下午从 01 到 12 的小时。当您不提供和解析 AM/PM 标记时,AM 用作默认。而 12:33:33 AM 表示午夜过后半小时多一点,在 24 小时制中呈现为 00:33:33。

从 13:00 到 23:59 的次数?它们不存在于 AM 中。显然 SimpleDateFormat 不关心,只是从 01 到 11 的时间推断,因此恰好给了你预期的时间。有一个技巧可以告诉它不要这样做;但我不想打扰,我宁愿根本不使用 class。

Link

Oracle tutorial: Date Time 解释如何使用 java.time.