# Easy methods to Calculate Minutes to Midnight in Java

0
7

## The problem#

Write a perform minutesToMidnight(d) that may take a date object because the parameter. Return the variety of minutes within the following format:

“x minute(s)”

You’ll all the time get a date object with of right this moment with a random timestamp.
It’s a must to around the variety of minutes.
Milliseconds don’t matter!`Some examples: 10.00 am => "840 minutes" 23.59 pm => "1 minute"`

## The answer in Java code#

Possibility 1:

``````import java.util.Date;

public class Minute {
public String countMinutes(Date d){
int minutes=(24-d.getHours()-1)*60+60-d.getMinutes();
if (d.getHours()==23 && d.getMinutes()==59) return "1 minute";
return (d.getSeconds()!=0)?  ""+(mins-1)+" minutes" : ""+minutes+" minutes";
}
}
``````

Possibility 2:

``````import static java.time.ZoneOffset.UTC;
import static java.time.temporal.ChronoField.MINUTE_OF_DAY;
import java.util.Date;

class Minute {
static String countMinutes(Date d) {
var time = d.toInstant().atZone(UTC);
int min = 1440 - time.get(MINUTE_OF_DAY) - Math.min(time.getSecond(), 1);
return min + " minute" + (min == 1 ? "" : "s");
}
}
``````

Possibility 3:

``````import java.util.Date;
import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;
import java.time.ZoneId;

public class Minute {
public String countMinutes(Date d){
LocalDateTime right this moment = LocalDateTime.ofInstant(d.toInstant(), ZoneId.systemDefault());
LocalDateTime midnight = right this moment.plusDays(1)
.withHour(0)
.withMinute(0)
.withSecond(0)
.withNano(0);
lengthy minutesBetween = ChronoUnit.MINUTES.between(right this moment, midnight);
return minutesBetween > 1 ? minutesBetween + " minutes" : minutesBetween + " minute";
}
}
``````

## Take a look at circumstances to validate our answer#

``````import org.junit.Take a look at;
import static org.junit.Assert.assertEquals;
import org.junit.runners.JUnit4;
import java.util.Date;
import java.util.Random;
import java.util.Calendar;
import java.util.GregorianCalendar;

public class MinuteTest {
@Take a look at
public void exampleTests(){
Minute m = new Minute();
Calendar cal = new GregorianCalendar();
cal.set(Calendar.HOUR_OF_DAY, 12);
cal.set(Calendar.MINUTE, 0);
cal.set(Calendar.SECOND, 0);
cal.set(Calendar.MILLISECOND, 0);
Date d = cal.getTime();
assertEquals("720 minutes", m.countMinutes(d));

cal.set(Calendar.HOUR_OF_DAY, 23);
cal.set(Calendar.MINUTE, 59);
cal.set(Calendar.SECOND, 0);
cal.set(Calendar.MILLISECOND, 0);
d = cal.getTime();
assertEquals("1 minute", m.countMinutes(d));
}
}
``````