user3880721
user3880721

Reputation: 613

Time of the day in minutes Java

I am looking to calculate the number of minutes given the time of the day.

Eg.: when input is 11:34, the output should be 11*60+34. The date doesn't matter.

I only need it down to the minutes scale. Seconds, milliseconds... don't matter. Is there a method somewhere in Java doing this the neat way without me calculating it?

Right now, i'm using theTime.split(":"), theTime is a String holding "11:34" here, parsing the integers on each side and doing the calculation.

I saw Time but what I'm doing right now seemed more direct.

Nothing in Systems either.

Upvotes: 6

Views: 2501

Answers (5)

Rika
Rika

Reputation: 796

   Calendar rightNow = Calendar.getInstance();
            int hour = rightNow.get(Calendar.HOUR);
    int min  = rightNow.get(Calendar.MINUTE);
    System.out.println("TimeMinutes:" + hour * 60 + min);

EDIT: Except using split use the above.

Upvotes: 0

kant
kant

Reputation: 198

Hi maybe you could use JodaTime? Below example how to get number of minutes from parsed string and from current time. In java 8 there is similar api but I haven't found exactly method like minutesOfDay()

@Test
public void learnHowManyMinutesPassedToday() {
   DateTime time = DateTimeFormat.forPattern("HH:mm").parseDateTime("11:34");
   System.out.println(time.getMinuteOfDay());

   System.out.println(DateTime.now().getMinuteOfDay());
} 

Upvotes: 2

gkrls
gkrls

Reputation: 2664

There is no build in method for it. However here is a one-liner for it:

int timeInMins = Calendar.getInstance().get(Calendar.HOUR_OF_DAY) * 60 + Calendar.getInstance().get(Calendar.MINUTE);

Upvotes: 8

QandA
QandA

Reputation: 11

If you are looking to have input not from a String, take a look at

Java.util.Calendar.

It has Calendar.HOUR_OF_DAY and Calendar.HOUR and Calendar.MINUTE which could be your input. I'm not sure what the "neat" way of doing this would be. It is a simple calculation.

Upvotes: 1

Rahul Tripathi
Rahul Tripathi

Reputation: 172448

Your approach looks good and sound, however to answer your question it would be simple to say that there is no such build in method which does that. You have to calculate it the way you are doing it right now.

Upvotes: 2

Related Questions