0

I'm reading the data from CSV file. One of the fields is the time in the format H:mm, i.e. "8:00". How to convert this string value into the minutes (integer value), i.e. 8:00 = 8*60 = 480 minutes?

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();
Martijn Pieters
  • 963,270
  • 265
  • 3,804
  • 3,187
Klausos Klausos
  • 14,142
  • 48
  • 129
  • 212

4 Answers4

6

You can use java.text.SimpleDateFormat to convert String to Date. And then java.util.Calendar to extract hours and minutes.

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);
Michal
  • 591
  • 4
  • 10
3

Try something like this

    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);
Ruchira Gayan Ranaweera
  • 33,712
  • 16
  • 72
  • 110
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;
}
sasikp
  • 1
  • 2
0

Try this

        String str = "8:20";
        int ans = (Integer.parseInt(str.split(":")[0])* 60)+Integer.parseInt(str.split(":")[1]);
        System.out.println("Answer = "+ans);
Rakesh KR
  • 6,207
  • 5
  • 41
  • 51