How to Calculate Minutes to Midnight in Java

The challenge

Write a function minutesToMidnight(d) that will take a date object as the parameter. Return the number of minutes in the following format:

“x minute(s)”

You will always get a date object with of today with a random timestamp.
You have to round the number of minutes.
Milliseconds don’t matter!Some examples: 10.00 am => "840 minutes" 23.59 pm => "1 minute"

The solution in Java code

Option 1:

import java.util.Date; public class Minute { public String countMinutes(Date d){ int mins=(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" : ""+mins+" minutes"; } }
Code language: Java (java)

Option 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"); } }
Code language: Java (java)

Option 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 today = LocalDateTime.ofInstant(d.toInstant(), ZoneId.systemDefault()); LocalDateTime midnight = today.plusDays(1) .withHour(0) .withMinute(0) .withSecond(0) .withNano(0); long minutesBetween = ChronoUnit.MINUTES.between(today, midnight); return minutesBetween > 1 ? minutesBetween + " minutes" : minutesBetween + " minute"; } }
Code language: Java (java)

Test cases to validate our solution

import org.junit.Test; 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 { @Test 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)); } }
Code language: Java (java)
Tags:
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments