0

我正在从 CSV 文件中读取数据。其中一个字段是格式为 H:mm 的时间,即“8:00”。如何将此字符串值转换为分钟(整数值),即 8:00 = 8*60 = 480 分钟?

String csvFilename = "test.csv";
CSVReader csvReader = new CSVReader(new FileReader(csvFilename));
String[] row = null;
csvReader.readNext(); // to skip the headers
int i = 0;
while((row = csvReader.readNext()) != null) {
    int open = Integer.parseInt(row[0]);
}
csvReader.close();
4

4 回答 4

6

您可以使用java.text.SimpleDateFormat转换StringDate. 然后java.util.Calendar提取小时和分钟。

Calendar cal = Calendar.getInstance();

SimpleDateFormat sdf = new SimpleDateFormat("HH:mm");
Date date = sdf.parse("8:00");
cal.setTime(date);

int mins = cal.get(Calendar.HOUR)*60 + cal.get(Calendar.MINUTE);
于 2013-09-06T11:47:53.953 回答
3

尝试这样的事情

    String str = "8:10";
    int minutes=0;
     String[] arr= str.split(":");
    if(arr.length==2){
        minutes=Integer.parseInt(arr[0])*60+Integer.parseInt(arr[1]);
    }
    System.out.println(minutes);
于 2013-09-06T11:39:40.307 回答
0

Write something like this to convert into int

public int convertToMin(String hrmin) {
String[] tokens = hrmin.split(":");
int minutes = 0;
for (int i = tokens.length; i > 0; i--) {
    int value = Integer.parseInt(tokens[i - 1]);
    if (i == 1) {
        minutes += 60 * value;
    }
    else {
        minutes += value;
    }
  }
  return minutes;
}
于 2013-09-06T11:49:11.780 回答
0

尝试这个

        String str = "8:20";
        int ans = (Integer.parseInt(str.split(":")[0])* 60)+Integer.parseInt(str.split(":")[1]);
        System.out.println("Answer = "+ans);
于 2013-09-06T11:51:15.327 回答