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
  • 1,048,767
  • 296
  • 4,058
  • 3,343
Klausos Klausos
  • 15,308
  • 51
  • 135
  • 217
  • Are you reading `8:00` as an `int`? – devnull Sep 06 '13 at 11:37
  • If you don't want to **parse it by yourself** (index of ":" and two Integer.parseInt(), **did you try** it???) you may use (especially if you work with dates) **JodaTime** with its Interval class... – Adriano Repetti Sep 06 '13 at 11:37
  • @devnull: yes,but obviously it's impossible. that's why I opened this thread. – Klausos Klausos Sep 06 '13 at 11:38
  • Since Java 8 (which came out 6 months after this question was asked) you should use the `Duration` class for a duration of hours and minutes. For parsing your stirng like `8:00` there are some good suggestions under [this similar question: Java 8 Time API: how to parse string of format “mm:ss” to Duration?](https://stackoverflow.com/questions/24642495/java-8-time-api-how-to-parse-string-of-format-mmss-to-duration). – Ole V.V. Jan 17 '23 at 17:14

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
  • 611
  • 5
  • 11
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
  • 34,993
  • 17
  • 75
  • 115
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,357
  • 5
  • 40
  • 55