1. “1时5分32秒” , “5分32秒” , “32秒”字符串转换成分
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class FlexibleTimeConversion {
public static void main(String[] args) {
System.out.println("总分钟数: " + convertTimeToMinutes("1时5分32秒"));
System.out.println("总分钟数: " + convertTimeToMinutes("5分32秒"));
System.out.println("总分钟数: " + convertTimeToMinutes("32秒"));
}
public static int convertTimeToMinutes(String timeString) {
Pattern pattern = Pattern.compile("(?:(\\d+)时)?(?:(\\d+)分)?(?:(\\d+)秒)?");
Matcher matcher = pattern.matcher(timeString);
if (matcher.find()) {
int hours = matcher.group(1) != null ? Integer.parseInt(matcher.group(1)) : 0;
int minutes = matcher.group(2) != null ? Integer.parseInt(matcher.group(2)) : 0;
int seconds = matcher.group(3) != null ? Integer.parseInt(matcher.group(3)) : 0;
int totalMinutes = hours * 60 + minutes + seconds / 60;
return totalMinutes;
} else {
System.out.println("输入的时间格式不正确");
return 0;
}
}
}
2. “1时5分32秒” , “5分32秒” , “32秒”字符串转换成 “1:05:32” , "00:05:32 " , “00:00:32” (HH:mm:ss)时间格式
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class TimeFormatConversion {
public static void main(String[] args) {
System.out.println("格式化时间: " + convertTimeToFormattedString("1时5分32秒"));
System.out.println("格式化时间: " + convertTimeToFormattedString("5分32秒"));
System.out.println("格式化时间: " + convertTimeToFormattedString("32秒"));
}
public static String convertTimeToFormattedString(String timeString) {
Pattern pattern = Pattern.compile("(?:(\\d+)时)?(?:(\\d+)分)?(?:(\\d+)秒)?");
Matcher matcher = pattern.matcher(timeString);
if (matcher.find()) {
int hours = matcher.group(1) != null ? Integer.parseInt(matcher.group(1)) : 0;
int minutes = matcher.group(2) != null ? Integer.parseInt(matcher.group(2)) : 0;
int seconds = matcher.group(3) != null ? Integer.parseInt(matcher.group(3)) : 0;
String formattedTime = String.format("%02d:%02d:%02d", hours, minutes, seconds);
return formattedTime;
} else {
return "输入的时间格式不正确";
}
}
}