我正在尝试将存储在数据库中的时间转换为类型字符串,并以适当的格式打印它。我尝试使用 .replaceAll 。这导致5:3被替换为05:03,但也将17:3变为0107:03。有没有人对正确的方法有任何建议?
String moduleStartHour = (c.getString(c.getColumnIndex(database.KEY_MODULESTARTHOUR)));
String moduleStartMinute = (c.getString(c.getColumnIndex(database.KEY_MODULESTARTMINUTE)));
String newModuleStartHour= moduleStartHour.replaceAll("0", "00").replaceAll("1", "01").replaceAll("2", "03")
.replaceAll('4', "04").replaceAll("5", "05").replaceAll("6", "06").replaceAll("7", "07").replaceAll("8", "08")
.replaceAll("9", "09");
String newModuleStartMinute= moduleStartMinute.replaceAll("0", "00").replaceAll("1", "01").replaceAll("2", "03")
.replaceAll("4", "04").replaceAll("5", "05").replaceAll("6", "06").replaceAll("7", "07").replaceAll("8", "08")
.replaceAll("9", "09");
StringBuilder sb =new StringBuilder();
sb.append(newModuleStartHour).append(":").append(newModuleStartMinute);
String moduleStartTime = sb.toString();
答案 0 :(得分:2)
if (moduleStartHour.length() == 1)
moduleStartHour = "0" + moduleStartHour;
if (moduleStartMinute.length() == 1)
moduleStartMinute = "0" + moduleStartMinute;
StringBuilder sb =new StringBuilder();
sb.append(moduleStartHour).append(":").append(moduleStartMinute);
String moduleStartTime = sb.toString();
或者我们将StringBuilder用于整个过程
StringBuilder sb = new StringBuilder();
if (moduleStartHour.length() == 1)
sb.append("0");
sb.append(moduleStartHour).append(":");
if (moduleStartMinute.length() == 1)
sb.append("0");
sb.append(moduleStartMinute);
String moduleStartTime = sb.toString();