Search code examples
javastringcsvinteger

Convert the string "8:00" into the minutes (integer value)


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();

Solution

  • 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);