【问题标题】:Split string and convert to int拆分字符串并转换为 int
【发布时间】:2015-12-02 17:06:41
【问题描述】:

我正在尝试使用以下代码将 String 时间转换为 int

public static int SplitTime(String time) {
    try {
        String[] altSplitTime = time.split(":",2);
        Log.e("2",altSplitTime[1]);
        return Integer.valueOf(altSplitTime[0]) * 60 + Integer.valueOf(altSplitTime[1]);
    }
    catch (Exception ex)
    {
        return 0;
    }
}

String 时间保持 Time In : 8:45 使用 split 方法后,我可以得到8:45

现在我想在return Integer.valueOf(altSplitTime[0]) * 60 + Integer.valueOf(altSplitTime[1]); 中获取(8*60) + 45。我该怎么做?

【问题讨论】:

  • 我认为既然你发布它目前不起作用......现在有什么问题?它会返回错误的东西吗?它什么都不返回吗?有例外吗?您提供的信息越多,获得帮助的机会就越大。
  • 我的代码没有问题。现在我只想拆分8:45

标签: android datetime split


【解决方案1】:

因为'time'中出现了两次“:”,所以需要将String分成三部分:

try {
    String[] altSplitTime = time.split(":",3);
    return Integer.valueOf( (altSplitTime[1]).trim() ) * 60 + Integer.valueOf( (altSplitTime[2]).trim() );
}
catch (Exception ex)
{
    return 0;
}

为了安全起见,我添加了trim() 来删除空格。

【讨论】:

    【解决方案2】:

    为什么不完全拆分呢? time.split(":",2); 将改为 time.split(":",3);

    这应该在您的示例['Time In', '8', '45'] 中为您提供数组中的三个值。

    然后您可以解析为 int 8 和 45 来进行计算。

    【讨论】:

      【解决方案3】:

      我会使用SimpleDateFormatCalendar

      SimpleDateFormat dateFormat = new SimpleDateFormat("H:mm");
      Date date = dateFormat.parse("8:45");
      Calendar calendar = Calendar.getInstance();
      calendar.setTime(date);
      

      然后您可以使用Calendar.get() 从您的字符串中检索hoursminutes 并使用Calendar.set 设置新值并将日历保留的日期格式化回String

      【讨论】:

        【解决方案4】:
        int a = Integer.parseInt(s3);
        int b = Integer.parseInt(s5);
        

        在你的情况下:

        public static int SplitTime(String time) {
        try {
            String[] altSplitTime = time.split(":",2);
            Log.e("2",altSplitTime[1]);
        
            int a = Integer.parseInt(altSplitTime[0]);
            int b = Integer.parseInt(altSplitTime[1]);
            return a * 60 + b;
        }
        catch (Exception ex)
        {
            return 0;
        }
        }
        

        【讨论】:

        • altSplitTime[0] 返回Time In
        • 如我的帖子中所述..如果您不清楚,我很抱歉 :)
        猜你喜欢
        • 1970-01-01
        • 2016-02-29
        • 1970-01-01
        • 1970-01-01
        • 2019-03-25
        • 2010-10-29
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多