java - 格式 hh :mm:ss 的解析时间

标签 java date string-parsing

如何解析 hh:mm:ss 格式的时间,作为字符串输入,在java中仅获取整数值(忽略冒号)?

最佳答案

根据 Basil Bourque 的评论,考虑到 Java 8 的新 API,这是该问题的更新答案:

    String myDateString = "13:24:40";
    LocalTime localTime = LocalTime.parse(myDateString, DateTimeFormatter.ofPattern("HH:mm:ss"));
    int hour = localTime.get(ChronoField.CLOCK_HOUR_OF_DAY);
    int minute = localTime.get(ChronoField.MINUTE_OF_HOUR);
    int second = localTime.get(ChronoField.SECOND_OF_MINUTE);

    //prints "hour: 13, minute: 24, second: 40":
    System.out.println(String.format("hour: %d, minute: %d, second: %d", hour, minute, second));

备注:

  • 由于OP的问题包含仅包含小时,分钟和秒(没有日,月等)的时间瞬间的具体示例,因此上面的答案仅使用LocalTime 。如果要解析还包含天、月等的字符串,则 LocalDateTime将被要求。它的用法与 LocalTime 非常相似。
  • 由于 time instant int OP 的问题不包含任何有关时区的信息,因此答案使用日期/时间类的 LocalXXX 版本(LocalTime、LocalDateTime)。如果需要解析的时间字符串还包含时区信息,则ZonedDateTime需要使用。

====== 下面是这个问题的旧(原始)答案,使用 Java8 之前的 API:=====

如果我的回答让任何人感到不安,我很抱歉,但我实际上会回答这个问题。 Java API 相当庞大,我认为有人时不时地错过一个是很正常的。

SimpleDateFormat 可能会在这里发挥作用:

http://docs.oracle.com/javase/7/docs/api/java/text/SimpleDateFormat.html

应该是这样的:

String myDateString = "13:24:40";
//SimpleDateFormat sdf = new SimpleDateFormat("hh:mm:ss");
//the above commented line was changed to the one below, as per Grodriguez's pertinent comment:
SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");
Date date = sdf.parse(myDateString);

Calendar calendar = GregorianCalendar.getInstance(); // creates a new calendar instance
calendar.setTime(date);   // assigns calendar to given date 
int hour = calendar.get(Calendar.HOUR);
int minute; /... similar methods for minutes and seconds

您应该注意的问题:

  • 您传递给 SimpleDateFormat 的模式可能与我的示例中的模式不同,具体取决于您拥有的值(是 12 小时格式还是 24 小时格式等)。有关详细信息,请参阅链接中的文档

  • 一旦您从 String 中创建了 Date 对象(通过 SimpleDateFormat),就不要试图使用 Date.getHour()、Date.getMinute() 等。它们有时可能会起作用,但是总的来说,它们可能会产生不好的结果,因此现在已被弃用。请使用日历,如上例所示。

关于java - 格式 hh :mm:ss 的解析时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60792949/

相关文章:

javascript - 搜索数字字符串

java - 如何通过持久性动态配置数据库连接

java - 子项目未编译Java/Android Studio

javascript - Moment js在特定时区创建日期时间

java - ParseException 尝试从其中包含 + 的字符串中解析日期

java - Android 日期格式类似于 gmail

c++ - 在 C++ 中将字符串转换为罗马数字

java - 在Java中获取字符串整数结尾的最佳方法?

android - 无法构建我的第一个 Android 程序

java - 在自定义 Web 应用程序中生成 LTPAToken 2