格式化时间hh:mm:ss

时间:2022-01-12 01:50:55

How can I parse a time of format hh:mm:ss , inputted as a string to obtain only the integer values (ignoring the colons) in java?

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

5 个解决方案

#1


67  

As per Basil Bourque's comment, this is the updated answer for this question, taking into account the new API of Java 8:

根据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));

Remarks:

  • since the OP's question contains a concrete example of a time instant containing only hours, minutes and seconds (no day, month, etc.), the answer above only uses LocalTime. If wanting to parse a string that also contains days, month, etc. then LocalDateTime would be required. Its usage is pretty much analogous to that of LocalTime.
  • 由于OP的问题包含一个仅包含小时,分钟和秒(没有日,月等)的时间瞬间的具体示例,上面的答案仅使用LocalTime。如果想要解析也包含天,月等的字符串,则需要LocalDateTime。它的用法非常类似于LocalTime。

  • since the time instant int OP's question doesn't contain any information about timezone, the answer uses the LocalXXX version of the date/time classes (LocalTime, LocalDateTime). If the time string that needs to be parsed also contains timezone information, then ZonedDateTime needs to be used.
  • 因为OP的问题的时刻不包含任何关于时区的信息,所以答案使用LocalXXX版本的日期/时间类(LocalTime,LocalDateTime)。如果需要解析的时间字符串也包含时区信息,则需要使用ZonedDateTime。

====== Below is the old (original) answer for this question, using pre-Java8 API: =====

======以下是此问题的旧(原始)答案,使用pre-Java8 API:=====

I'm sorry if I'm gonna upset anyone with this, but I'm actually gonna answer the question. The Java API's are pretty huge, I think it's normal that someone might miss one now and then.

我很抱歉,如果我对这个人感到不安,但我真的要回答这个问题。 Java API非常庞大,我认为有人可能会偶尔错过一个。

A SimpleDateFormat might do the trick here:

SimpleDateFormat可以在这里做到这一点:

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

It should be something like:

它应该是这样的:

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

The gotchas you should be aware of:

你应该知道的陷阱:

  • the pattern you pass to SimpleDateFormat might be different then the one in my example depending on what values you have (are the hours in 12 hours format or in 24 hours format, etc). Look at the documentation in the link for details on this

    您传递给SimpleDateFormat的模式可能与我的示例中的模式不同,具体取决于您拥有的值(12小时格式或24小时格式的小时数等)。请查看链接中的文档以获取详细信息

  • Once you create a Date object out of your String (via SimpleDateFormat), don't be tempted to use Date.getHour(), Date.getMinute() etc. They might appear to work at times, but overall they can give bad results, and as such are now deprecated. Use the calendar instead as in the example above.

    一旦你从你的String中创建一个Date对象(通过SimpleDateFormat),不要试图使用Date.getHour(),Date.getMinute()等。它们似乎有时会起作用,但总的来说它们会给出不好的结果,现在已经弃用了。请使用日历,如上例所示。

#2


10  

A bit verbose, but it's the standard way of parsing and formatting dates in Java:

有点冗长,但它是在Java中解析和格式化日期的标准方法:

DateFormat formatter = new SimpleDateFormat("HH:mm:ss");
try {
  Date dt = formatter.parse("08:19:12");
  Calendar cal = Calendar.getInstance();
  cal.setTime(dt);
  int hour = cal.get(Calendar.HOUR);
  int minute = cal.get(Calendar.MINUTE);
  int second = cal.get(Calendar.SECOND);
} catch (ParseException e) {
  // This can happen if you are trying to parse an invalid date, e.g., 25:19:12.
  // Here, you should log the error and decide what to do next
  e.printStackTrace();
}

#3


4  

String time = "12:32:22";
String[] values = time.split(":");

This will take your time and split it where it sees a colon and put the value in an array, so you should have 3 values after this.

这将耗费你的时间并将其拆分到看到冒号的位置并将值放在数组中,因此在此之后你应该有3个值。

Then loop through string array and convert each one. (with Integer.parseInt)

然后循环遍历字符串数组并转换每一个。 (使用Integer.parseInt)

#4


1  

If you want to extract the hours, minutes and seconds, try this:

如果要提取小时,分钟和秒,请尝试以下操作:

String inputDate = "12:00:00";
String[] split = inputDate.split(":");
int hours = Integer.valueOf(split[0]);
int minutes = Integer.valueOf(split[1]);
int seconds = Integer.valueOf(split[2]);

#5


-3  

you can use method toCharArray() return data like: array("1","2",":","0","1",":","0","0") <- these are char in java or you can convert the string to Date + try catch => then get hour, minutes & seconds

你可以使用方法toCharArray()返回数据,如:array(“1”,“2”,“:”,“0”,“1”,“:”,“0”,“0”)< - 这些是char在java中你可以将字符串转换为Date + try catch =>然后获取小时,分钟和秒

#1


67  

As per Basil Bourque's comment, this is the updated answer for this question, taking into account the new API of Java 8:

根据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));

Remarks:

  • since the OP's question contains a concrete example of a time instant containing only hours, minutes and seconds (no day, month, etc.), the answer above only uses LocalTime. If wanting to parse a string that also contains days, month, etc. then LocalDateTime would be required. Its usage is pretty much analogous to that of LocalTime.
  • 由于OP的问题包含一个仅包含小时,分钟和秒(没有日,月等)的时间瞬间的具体示例,上面的答案仅使用LocalTime。如果想要解析也包含天,月等的字符串,则需要LocalDateTime。它的用法非常类似于LocalTime。

  • since the time instant int OP's question doesn't contain any information about timezone, the answer uses the LocalXXX version of the date/time classes (LocalTime, LocalDateTime). If the time string that needs to be parsed also contains timezone information, then ZonedDateTime needs to be used.
  • 因为OP的问题的时刻不包含任何关于时区的信息,所以答案使用LocalXXX版本的日期/时间类(LocalTime,LocalDateTime)。如果需要解析的时间字符串也包含时区信息,则需要使用ZonedDateTime。

====== Below is the old (original) answer for this question, using pre-Java8 API: =====

======以下是此问题的旧(原始)答案,使用pre-Java8 API:=====

I'm sorry if I'm gonna upset anyone with this, but I'm actually gonna answer the question. The Java API's are pretty huge, I think it's normal that someone might miss one now and then.

我很抱歉,如果我对这个人感到不安,但我真的要回答这个问题。 Java API非常庞大,我认为有人可能会偶尔错过一个。

A SimpleDateFormat might do the trick here:

SimpleDateFormat可以在这里做到这一点:

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

It should be something like:

它应该是这样的:

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

The gotchas you should be aware of:

你应该知道的陷阱:

  • the pattern you pass to SimpleDateFormat might be different then the one in my example depending on what values you have (are the hours in 12 hours format or in 24 hours format, etc). Look at the documentation in the link for details on this

    您传递给SimpleDateFormat的模式可能与我的示例中的模式不同,具体取决于您拥有的值(12小时格式或24小时格式的小时数等)。请查看链接中的文档以获取详细信息

  • Once you create a Date object out of your String (via SimpleDateFormat), don't be tempted to use Date.getHour(), Date.getMinute() etc. They might appear to work at times, but overall they can give bad results, and as such are now deprecated. Use the calendar instead as in the example above.

    一旦你从你的String中创建一个Date对象(通过SimpleDateFormat),不要试图使用Date.getHour(),Date.getMinute()等。它们似乎有时会起作用,但总的来说它们会给出不好的结果,现在已经弃用了。请使用日历,如上例所示。

#2


10  

A bit verbose, but it's the standard way of parsing and formatting dates in Java:

有点冗长,但它是在Java中解析和格式化日期的标准方法:

DateFormat formatter = new SimpleDateFormat("HH:mm:ss");
try {
  Date dt = formatter.parse("08:19:12");
  Calendar cal = Calendar.getInstance();
  cal.setTime(dt);
  int hour = cal.get(Calendar.HOUR);
  int minute = cal.get(Calendar.MINUTE);
  int second = cal.get(Calendar.SECOND);
} catch (ParseException e) {
  // This can happen if you are trying to parse an invalid date, e.g., 25:19:12.
  // Here, you should log the error and decide what to do next
  e.printStackTrace();
}

#3


4  

String time = "12:32:22";
String[] values = time.split(":");

This will take your time and split it where it sees a colon and put the value in an array, so you should have 3 values after this.

这将耗费你的时间并将其拆分到看到冒号的位置并将值放在数组中,因此在此之后你应该有3个值。

Then loop through string array and convert each one. (with Integer.parseInt)

然后循环遍历字符串数组并转换每一个。 (使用Integer.parseInt)

#4


1  

If you want to extract the hours, minutes and seconds, try this:

如果要提取小时,分钟和秒,请尝试以下操作:

String inputDate = "12:00:00";
String[] split = inputDate.split(":");
int hours = Integer.valueOf(split[0]);
int minutes = Integer.valueOf(split[1]);
int seconds = Integer.valueOf(split[2]);

#5


-3  

you can use method toCharArray() return data like: array("1","2",":","0","1",":","0","0") <- these are char in java or you can convert the string to Date + try catch => then get hour, minutes & seconds

你可以使用方法toCharArray()返回数据,如:array(“1”,“2”,“:”,“0”,“1”,“:”,“0”,“0”)< - 这些是char在java中你可以将字符串转换为Date + try catch =>然后获取小时,分钟和秒