How to Transform Time String to an Entire?

Asked

Viewed 1,407 times

5

Example, I get a String with the "16:20" time of day. The day is 1440 minutes long. How to know what interval from zero to 1440 is this time? In an integer value(integer).

2 answers

4


I don’t think I need a class like Calendar to solve, just one split and do a mathematical operation, like this:

String horacompleta = "12:39";
String[] horamin = horacompleta.split(":");

int hora = Integer.parseInt(horamin[0]);
int min = Integer.parseInt(horamin[1]);

int minutos = (hora * 60) + min; //Pega o total

You can put in a function like this:

public static int hour2minutes(String fullhour)
{
    String[] parts = fullhour.split(":");

    int hour = Integer.parseInt(parts[0]);
    int min = Integer.parseInt(parts[1]);

    return (hour * 60) + min;
}

And to use, do so:

hour2minutes("12:39"); //759
hour2minutes("16:20"); //980
hour2minutes("23:59"); //1439

See a test on IDEONE: https://ideone.com/amkZW8

4

There are several ways to do this. Another other than Guilherme would be, for example using the SimpleDataFormat to convert the string in date format, and then use the class TimeUnit converting milliseconds into minutes using the method toMinutes(). See how it would look:

public int hour2min(String hour) {
    try {
        Date date = new SimpleDateFormat("kk:mm").parse(hour);
        return (int) (TimeUnit.MILLISECONDS.toMinutes(date.getTime())-180);
    } catch (ParseException e) {
        e.printStackTrace();
        return 0;
    }
}

To use just do so:

Log.wtf("",""+hour2min("18:23"));

Exit:

1103
  • 1

    Very good this because it validates the +1 input data

  • @Guilhermenascimento took the name of the function there from his suggestion: "hour2min" -Utes

Browser other questions tagged

You are not signed in. Login or sign up in order to post.