1

我正在尝试将存储在数据库中的时间转换为类型字符串并以适当的格式打印。我尝试使用.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();
4

1 回答 1

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();
于 2012-11-05T21:58:03.943 回答