Totalling times in HHMM format - java

So i have a series of times:
ArrayList<String> times = new ArrayList<String>();
times.add("1240");
times.add("1028");
times.add("0923");
times.add("2023");
And I wan't to find the total hours traversed between these times, but I can't figure out how!
For example:
"1240 to 1028" would be 11hrs20 + 10hrs28 in travel time.
To go from 12h40 on one day to 10h28 next day, you need 11h20 (going to midnight), then 10h28. Quite clear.

First we need a way to convert a string into a linear time representation:
// Given a string of the form HHMM, this returns the number of minutes after midnight.
// For example: timeStringToMinutes("0000") -> 0.
// timeStringToMinutes("0015") -> 15.
// timeStringToMinutes("0100") -> 60.
// timeStringToMinutes("0837") -> 517.
// timeStringToMinutes("2359") -> 1439.
static int timeStringToMinutes(String s) {
return Integer.parseInt(s.substring(0, 2)) * 60 + Integer.parseInt(s.substring(2, 4));
}
Next we define a function to compute time differences:
// Example: forwardNumberOfMinutes("1240", "1028") -> 1308.
static int forwardNumberOfMinutes(String start, String end) {
int from = timeStringToMinutes(start);
int to = timeStringToMinutes(end);
if (to < from)
to += 1440; // 1 day, or 24 hours
return to - from;
}
Finally we define a function to convert linear time to hours and minutes:
// Example: minutesToTimeString(1308) -> "2148" (21 hr 48 min).
static minutesToTimeString(int n) {
return String.format("%02d%02d", n / 60, n % 60);
}

Related

Difference in time between strings

I was working on a coding challenge where the goal was to find the smallest time difference in a list of Strings. I gave up and looked at a solution which in all makes sense, but I'm confused on the method parseTime. Can anybody please explain this method?
As I see it, the two hours compared are subtracted and then multiplied by 60 (becuase 60 min in one hour?).
From that the minutes are compared and then I get lost.. Can anybody explain this as simple as possible?
public static void main(String[] args) {
String[] strings = {"10:00am", "11:45pm", "5:00am", "12:01am"};
int i = TimeDifference(strings);
System.out.println(i);
}
public static int TimeDifference(String[] strArr) {
int min = Integer.MAX_VALUE;
for (int i=0; i<strArr.length; i++) {
for (int j=0; j<strArr.length; j++) {
if (i != j) {
int time = parseTime(strArr[j], strArr[i]);
if (time < min) min = time;
}
}
}
return min;
}
private static int parseTime(String time1, String time2) {
int time = (parseHour(time2) - parseHour(time1))*60;
time += parseMin(time2) - parseMin(time1);
if (isMorning(time2) != isMorning(time1)) {
time += 12 *60;
} else if (time <= 0 ) {
time += 24 * 60;
}
return time;
}
private static int parseHour(String time) {
int hour = Integer.valueOf(time.split(":")[0]);
return ( hour == 12? 0: hour);
}
private static int parseMin(String time) {
return Integer.valueOf(time.split(":")[1].replaceAll("[^0-9]",""));
}
private static boolean isMorning(String time) {
String post = time.split(":")[1].replaceAll("[^a-z]","");
return post.toLowerCase().equals("am");
}
Try to debug your code in your mind. Please check my comments below:
int minutes = parseTime("10:00am", "11:45pm");
private static int parseTime(String time1, String time2) {
int minutes = (parseHour(time2) - parseHour(time1))*60;//(11 - 10) * 60 = 60 minutes
minutes += parseMin(time2) - parseMin(time1); //60 + 45 - 0 = 105 minutes
if (isMorning(time2) != isMorning(time1)) { // 10:00am is not morning but 11:45pm is morning
minutes += 12 *60; //so we have to add 12 hours(12 * 60 minutes)
} else if (minutes <= 0 ) {
minutes += 24 * 60;
}
return minutes;
}
This is about regular expressions (RegEx). Let's look at 11:45pm as an example, and break up parseTime:
int time = (parseHour(time2) - parseHour(time1))*60;
The first line makes use of parseHour, which makes use of split, which splits the string around matches of the given regular expression, ":", and then parses the string at index 0 as an integer.
The string "11:45pm" is split into a string array {"11", "45pm"}, and the integer 11 is returned.
time += parseMin(time2) - parseMin(time1);
The second line makes use of parseMin, which similarly splits the given string, but parses the string at index 1 instead. However, the string "45pm" cannot be parsed as an integer, because it contains the non-digits "pm", so we use replaceAll to replace any non-digits with empty strings.
replaceAll replaces each substring of this string that matches the given regular expression with the given replacement.
"[^0-9]" matches any single character not present in 0-9, which is all nondigits, so "45pm".replaceAll("[^0-9]", "") returns "45", which is then parsed as an integer.
The rest has been answered by others already.
Yes, the difference in hours are converted to minutes by multiplying by 60. Then using parseMin the difference in minutes are added to it.
Now we need it check if it is AM or PM. Example : if the times were 10:30 am and 1:35 pm. The actual time difference is +115 minutes.
After parseHour the time would have a value of -600 ((1-10)*60). Then after parseMin, time would be -595 (difference of 5 minutes added). Now we need to see if it is AM or PM. Since time1 is AM and time2 is PM, we add a difference of 12hrs. This is because the same time in AM and PM would differ by 12hrs.
After this the time would be (-605 + 720) = 115 minutes.
The case when time<=0. This is when time2 is before time1. example time1 be 10:35am and time2 be 10:30am. So the question is - how much time would it take to REACH 10:30am FROM 10:35am. Since it is alreaddy 10:35am and since we cannot go back in time, we need to wait till the next day(24 hrs) to reach 10:30am. So we add 24*60 minutes to the time, which would give -5 + (24*60)

Java how to remove last numbers of a long?

i'm working with a query to bring data acording to a given time. so i want to grab a timestamp an remove the last 3 digits of it. Is it possible? how? give me a hint i will totally apreciate that
If you want to REMOVE the digits, divide by 10^n:
long x = 1234567890L;
long removeLastNDigits(long x, long n) {
return x / Math.pow(10, n);
}
removeLastNDigits(x, 3) == 1234567L;
As pointed out by dasblinkenlight, if you want to 0 the last n digits then after removing them you need to add them back as 0:
long x = 1234567890L;
long zeroLastNDigits(long x, long n) {
long tenToTheN = Math.pow(10, n);
return (x / tenToTheN) * tenToTheN;
}
zeroLastNDigits(x, 3) == 1234567000L;
If you want to remove the last 3 digits, just divide by 1000 :
long l = ...;
l = l / 1000;
If you want to change the last 3 digits to 0, divide by 1000 and then multiple by 1000 :
long l = ...;
l = (l / 1000) * 1000;
just divide by 1000.
long x = 123456789L;
long withoutLast3 = x / 1000; // equals to 123456L
I think you should format your timestamp value according to the required format in the database, if that is what you are looking for that is fetching data based on date in a certain format.
You can format your date according based on a dateformatter and then use it in query.
Check
DateFormat
SimpleDateFormat

time difference in military time in Java

So for an assignment we had to write a program that takes two times in military time and shows the difference in hours and minutes between them assuming the first time is the earlier of the two times. We weren't allowed to use if statements as it technically has not be learned. Here's an example of what it'd look like run. In quotes I'll put what is manually entered when it is prompted to.
java MilitaryTime
Please enter first time: "0900"
Please enter second time: "1730"
8 hours 30 minutes (this is the final answer)
I was able to quite easily get this part done with the following code:
class MilitaryTime {
public static void main(String [] args) {
Scanner in = new Scanner(System.in);
System.out.println("Please enter the first time: ");
int FirstTime = in.nextInt();
System.out.println("Please enter the second time: ");
int SecondTime = in.nextInt();
int FirstHour = FirstTime / 100;
int FirstMinute = FirstTime % 100;
int SecondHour = SecondTime / 100;
int SecondMinute = SecondTime % 100;
System.out.println( ( SecondHour - FirstHour ) + " hours " + ( SecondMinute
- FirstMinute ) + " minutes " );
}
}
Now my question is something wasn't assigned (or I wouldn't be here!) is there's another part to this question in the book that says to take that program we just wrote and deal with the case where the first time is later than the second. This has really intrigued me about how this would be done and has really stumped me. Again we aren't allowed to use if statements or this would be easy we basically have all the mathematical functions to work with.
An example would be the first time is now 1730 and the second time is 0900 and so now it returns 15 hours 30 minutes.
I would like to suggest to use org.joda.time.DateTime. There are a lot of date and time functions.
Example :
SimpleDateFormat format = new SimpleDateFormat("dd-MM-yyyy hh:mm");
Date startDate = format.parse("10-05-2013 09:00");
Date endDate = format.parse("11-05-2013 17:30");
DateTime jdStartDate = new DateTime(startDate);
DateTime jdEndDate = new DateTime(endDate);
int years = Years.yearsBetween(jdStartDate, jdEndDate).getYears();
int days = Days.daysBetween(jdStartDate, jdEndDate).getDays();
int months = Months.monthsBetween(jdStartDate, jdEndDate).getMonths();
int hours = Hours.hoursBetween(jdStartDate, jdEndDate).getHours();
int minutes = Minutes.minutesBetween(jdStartDate, jdEndDate).getMinutes();
System.out.println(hours + " hours " + minutes + " minutes");
Your expected program will be as below :
SimpleDateFormat format = new SimpleDateFormat("hhmm");
Dates tartDate = format.parse("0900");
Date endDate = format.parse("1730");
DateTime jdStartDate = new DateTime(startDate);
DateTime jdEndDate = new DateTime(endDate);
int hours = Hours.hoursBetween(jdStartDate, jdEndDate).getHours();
int minutes = Minutes.minutesBetween(jdStartDate, jdEndDate).getMinutes();
minutes = minutes % 60;
System.out.println(hours + " hours " + minutes + " minutes");
Output :
8 hours 30 minutes
Normally, when dealing with time calculations of this nature I would use Joda-Time, but assuming that you don't care about the date component and aren't rolling over the day boundaries, you could simply convert the value to minutes or seconds since midnight...
Basically the problem you have is the simple fact that there are 60 minutes in an hour, this makes doing simple mathematics impossible, you need something which is more common
For example, 0130 is actually 90 minutes since midnight, 1730 is 1050 minutes since midnight, which makes it 16 hours in difference. You can simply subtract the two values to get the difference, then convert that back to hours and minutes...for example...
public class MilTimeDif {
public static void main(String[] args) {
int startTime = 130;
int endTime = 1730;
int startMinutes = minutesSinceMidnight(startTime);
int endMinutes = minutesSinceMidnight(endTime);
System.out.println(startTime + " (" + startMinutes + ")");
System.out.println(endTime + " (" + endMinutes + ")");
int dif = endMinutes - startMinutes;
int hour = dif / 60;
int min = dif % 60;
System.out.println(hour + ":" + min);
}
public static int minutesSinceMidnight(int milTime) {
double time = milTime / 100d;
int hours = (int) Math.floor(time);
int minutes = milTime % 100;
System.out.println(hours + ":" + minutes);
return (hours * 60) + minutes;
}
}
Once you start including the date component or rolling over day boundaries, get Joda-Time out
I would do something like:
System.out.println(Math.abs( SecondHour - FirstHour ) + " hours " + Math.abs( SecondMinute - FirstMinute ) + " minutes " );
The absolute value will give you the difference between the two times as a positive integer.
You could do something like this
//Code like you already have
System.out.println("Please enter the first time: ");
int firstTime = in.nextInt();
System.out.println("Please enter the second time: ");
int secondTime = in.nextInt();
//Now we can continue using the code you already wrote by
//forcing the smaller of the two times into the 'firstTime' variable.
//This forces the problem to be the same situation as you had to start with
if (secondTime < firstTime) {
int temp = firstTime;
firstTime = secondTime;
secondTime = temp;
}
//Continue what you already wrote
There are many other ways but this was something I used for similar problems while learning. Also, note that I changed variable names to follow java naming conventions - variables are lowerCamelCase.
I used 3 classes. Lets go over theory first.
We have two times: A and B.
if AtimeDiff = (B-A).....which can be written -(A-B)
if A>B, then timeDiff = 1440- (A-B) [1440 is total minutes in day]
Thus we need to make timeDiff = 1440 - (A-B) and we need to make 1440 term dissapear when A
Lets make a term X = (A-B+1440) / 1440 (notice "/" is integer division.
'if A
'if A>B then X = 1;
Now look at a new term Y = 1440 * X.
'if A
'if A>B then Y = 1440'.
PROBLEM SOLVED. Now just plug into Java Programs. Note what happens if A=B. Our program will assume we know no time passes if times are exact same time. It assumes that 24 hours have passed. Anyways check out the 3 programs listed below:
Class #1
public class MilitaryTime {
/**
* MilitaryTime A time has a certain number of minutes passed at
* certain time of day.
* #param milTime The time in military format
*/
public MilitaryTime(String milTime){
int hours = Integer.parseInt(milTime.substring(0,2));
int minutes = Integer.parseInt(milTime.substring(2,4));
timeTotalMinutes = hours * 60 + minutes;
}
/**
* Gets total minutes of a Military Time
* #return gets total minutes in day at certain time
*/
public int getMinutes(){
return timeTotalMinutes;
}
private int timeTotalMinutes;
}
Class#2
public class TimeInterval {
/**
A Time Interval is amount of time that has passed between two times
#param timeA first time
#param timeB second time
*/
public TimeInterval(MilitaryTime timeA, MilitaryTime timeB){
// A will be shorthand for timeA and B for timeB
// Notice if A<B timeDifferential = TOTAL_MINUTES_IN_DAY - (A - B)
// Notice if A>B timeDifferential = - (A - B)
// Both will use timeDifferential = TOTAL_MINUTES_IN_DAY - (A - B),
// but we need to make TOTAL_MINUTES_IN_DAY dissapear when needed
//Notice A<B following term "x" is 1 and if A>B then it is 0.
int x = (timeA.getMinutes()-timeB.getMinutes()+TOTAL_MINUTES_IN_DAY)
/TOTAL_MINUTES_IN_DAY;
// Notice if A<B then term "y" is TOTAL_MINUTES_IN_DAY(1440 min)
// and if A<B it is 0
int y = TOTAL_MINUTES_IN_DAY * x;
//yay our TOTAL_MINUTES_IN_DAY dissapears when needed.
int timeDifferential = y - (timeA.getMinutes() - timeB.getMinutes());
hours = timeDifferential / 60;
minutes = timeDifferential % 60;
//Notice that if both hours are equal, 24 hours will be shown.
// I assumed that we would knoe if something start at same time it
// would be "0" hours passed
}
/**
* Gets hours passed between 2 times
* #return hours of time difference
*/
public int getHours(){
return hours;
}
/**
* Gets minutes passed after hours accounted for
* #return minutes remainder left after hours accounted for
*/
public int getMinutes(){
return minutes;
}
private int hours;
private int minutes;
public static final int TOTAL_MINUTES_IN_DAY = 1440;//60minutes in 24 hours
}
Class#3
import java.util.Scanner;
public class MilitaryTimeTester {
public static void main (String[] args){
Scanner in = new Scanner(System.in);
System.out.println("Enter time A: ");
MilitaryTime timeA = new MilitaryTime(in.nextLine());
System.out.println("Enter time B: ");
MilitaryTime timeB = new MilitaryTime(in.nextLine());
TimeInterval intFromA2B = new TimeInterval(timeA,timeB);
System.out.println("Its been "+intFromA2B.getHours()+" hours and "+intFromA2B.getMinutes()+" minutes.");
}
}
import java.util.Scanner;
public class TimeDifference{
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
// read first time
System.out.println("Please enter the first time: ");
int firstTime = in.nextInt();
// read second time
System.out.println("Please enter the second time: ");
int secondTime = in.nextInt();
in.close();
// if first time is more than second time, then the second time is in
// the next day ( + 24 hours)
if (firstTime > secondTime)
secondTime += 2400;
// first hour & first minutes
int firstHour = firstTime / 100;
int firstMinute = firstTime % 100;
// second hour & second minutes
int secondHour = secondTime / 100;
int secondMinute = secondTime % 100;
// time difference
int hourDiff = secondHour - firstHour;
int minutesDiff = secondMinute - firstMinute;
// adjust negative minutes
if (minutesDiff < 0) {
minutesDiff += 60;
hourDiff--;
}
// print out the result
System.out.println(hourDiff + " hours " + minutesDiff + " minutes ");
}
}
This one is done without using ifs and date thingy. you just need to use integer division "/", integer remainder thing"%", and absolute value and celing. might be able to be simplified but im too lazy at moment. I struggled for hours to figure out and seems nobody else got the answer without using more advanced functions. this problem was in Cay Horstmann's Java book. Chapter 4 in Java 5-6 version of the book "Java Concepts"
import java.util.Scanner;
public class MilitaryTime {
public static void main (String[] args){
//creates input object
Scanner in = new Scanner(System.in);
System.out.println("Enter time A: ");
String timeA = in.next();
System.out.println("Enter time B: ");
String timeB = in.next();
//Gets the hours and minutes of timeA
int aHours = Integer.parseInt(timeA.substring(0,2));
int aMinutes = Integer.parseInt(timeA.substring(2,4));
//Gets the hours and minutes of timeB
int bHours = Integer.parseInt(timeB.substring(0,2));
int bMinutes = Integer.parseInt(timeB.substring(2,4));
//calculates total minutes for each time
int aTotalMinutes = aHours * 60 + aMinutes;
int bTotalMinutes = bHours * 60 + bMinutes;
//timeA>timeB: solution = (1440minutes - (aTotalMinutes - bTotalMinutes))
//timeA<timeB: solution is (bTotalMinutes - aTotalMinutes) or
//-(aTotalMinutes - bTotalMinutes)
//we need 1440 term when timea>timeeB... we use mod and mod remainder
//decider is 1 if timeA>timeB and 0 if opposite.
int decider = ((aTotalMinutes - bTotalMinutes +1440)/1440);
// used 4 Special case when times are equal. this way we get 0
// timeDiffference term when equal and 1 otherwise.
int equalsDecider = (int) Math.abs((aTotalMinutes - bTotalMinutes));
//fullDayMaker is used to add the 1440 term when timeA>timeB
int fullDayMaker = 1440 * decider;
int timeDifference = (equalsDecider)* (fullDayMaker - (aTotalMinutes - bTotalMinutes));
// I convert back to hours and minmutes using modulater
System.out.println(timeDifference/60+" hours and "+timeDifference%60+" minutes");
}
}
java.time
Java 8 and later includes the new java.time framework. See the Tutorial.
The new classes include LocalTime for representing a time-only value without date and without time zone.
Another class is Duration, for representing a span of time as a total number of seconds and nanoseconds. A Duration may be viewed as a number of hours and minutes.
By default the Duration class implements the toString method to generate a String representation of the value using the ISO 8601 format of PnYnMnDTnHnMnS where the P marks the beginning and the T separates the date portion from the time portion. The Duration class can parse as well as generate strings in this standard format.
So, the result in example code below is PT8H30M for eight and a half hours. This format is more sensible than 08:30 which can so easily be confused for a time rather than a duration.
String inputStart = "0900";
String inputStop = "1730";
DateTimeFormatter formatter = DateTimeFormatter.ofPattern ( "HHmm" );;
LocalTime start = formatter.parse ( inputStart , LocalTime :: from );
LocalTime stop = formatter.parse ( inputStop , LocalTime :: from );
Duration duration = Duration.between ( start , stop );
Dump to console.
System.out.println ( "From start: " + start + " to stop: " + stop + " = " + duration );
When run.
From start: 09:00 to stop: 17:30 = PT8H30M
import java.util.*;
class Time
{
static Scanner in=new Scanner(System.in);
public static void main(String[] args)
{
int time1,time2,totalTime;
System.out.println("Enter the first time in military:");
time1=in.nextInt();
System.out.println("Enter the second time in military:");
time2=in.nextInt();
totalTime=time2-time1;
String temp=Integer.toString(totalTime);
char hour=temp.charAt(0);
String min=temp.substring(1,3);
System.out.println(hour+" hours "+min+" minutes");
}
}

Convert simple time format to Special time format (hhmmt)

I'm trying to convert the time format (hh:mm:ss) to this Special Time Format (hhmmt)?
The Special Time Format (STF) is a 5 digit integer value with the format [hhmmt] where hh are the hours, mm are the minutes and t is the tenth of a minute.
For example, 04:41:05 would convert to 4411.
I'm not sure how to convert the seconds value (05) to a tenth of a minute (1).
Edit:
I've incorporated Adithya's suggestion below to convert seconds to a tenth of a minute, but I'm still stuck.
Here is my current code:
String[] timeInt = time.split(":");
String hours = timeInt[0];
String minutes = timeInt[1];
double seconds = Double.parseDouble(timeInt[2]);
int t = (int) Math.round(seconds/6);
if (t>=10) {
int min = Integer.parseInt(minutes);
// min+=1;
t = 0;
}
String stf="";
stf += hours;
stf += minutes;
stf += String.valueOf(t);
int stf2 = Integer.parseInt(stf);
return stf2;
I'm using a String to store the minutes value but it makes it difficult to increment it since it is a String and not a Integer. But when calculating the "t" (tenth of minute) I have to add 1 to minutes if it exceeds 10. If I were to use parseInt again it will exclude the 0 in front of minutes again.
How can I retain the leading zero and still increment the minutes?
Thanks.
I am guessing, its the value of seconds, compared to the tenth of a minute, which is 6 seconds. So formula for t would be
t= seconds/6 //rounded off to nearest integer
This makes sense as this value is always between 0 and 9, as seconds range from 0 and 59, so its always a single digit
For your example
t = 5/6 = 0.833 = rounded off to 1
Note the 6.0f in the division - this helps you avoid the INT truncation.
string FormatSpecialTime(string time)
{
if (time.Length != 8) throw YourException();
int HH, mm, SS, t;
if (!int.TryParse(time.Substring(0, 2), out HH)) HH = 0;
if (!int.TryParse(time.Substring(0, 2), out mm)) mm = 0;
if (!int.TryParse(time.Substring(0, 2), out SS)) SS = 0;
t = (int) Math.Round(SS / 6.0f);
if (t >= 10)
{
mm++;
t = 0;
}
if (mm >= 60)
{
HH += mm / 60;
mm = mm % 60;
}
return HH.ToString() + (mm > 10 ? mm.ToString() : #"0" + mm) + t;
}

Sum of the bits in Java

sorry Friends i did a mistake. I have did this mistake again. am really very sorry.
this is the Issue.
I have a time range like
int Starttime = 2 which mean(02:00)
int enttime = 8 which mean(08:00)
i want time in sum of bits,
example
00:00 1
01:00 2
02:00 4 -----
03:00 8 R
04:00 16 a
05:00 32 n
06:00 64 g
07:00 128 e
08:00 256 -----
and soo on till 23:00
so i need totalRange = 256+128+64+32+16+8+4 ;
it should be like this
sorry again.
Thanks
The table indicates that you want to map the hour value of a time to an integer value using this function:
int value = (int) Math.pow(2, hourValue);
or, in other words, 00:00h will map to 20, 12:00h to 212 and so on.
Now if you have need the sum of start and endtime, you can simple use the function from above and add the values:
int totalrange = (int) Math.pow(2, starttime) + (int) Math.pow(2, endtime);
Now if you have starttime=2 and endtime=23, this will give a result (written in binary):
01000000 00000000 00000100
shamelessly adapting polygenelubricants much faster solution:
int totalrange = (1 << starttime) + (1 << endtime);
This works, because 2i is equal to (1 << i).
System.out.println(Integer.toBinaryString(2+24)); // 11010
This uses the Integer.toBinaryString method. There's also toHexString, toOctalString, and a toString with variable radix.
If you need the string to be zero-padded to a specific width, you can write something simple like this:
static String binaryPadded(int n, int width) {
String s = Integer.toBinaryString(n);
return "00000000000000000000000000000000"
.substring(0, width - s.length()) + s;
}
//...
System.out.println(binaryPadded(2+24, 8)); // 00011010
There are different ways to zero pad a string to a fixed width, but this will work for any int value.
For hexadecimal or octal, you can use formatting string instead:
System.out.println(String.format("%04X", 255)); // 00FF
The specification isn't very clear, but it looks like you want this mapping:
0 -> 1
1 -> 2
2 -> 4
3 -> 8
4 -> 16
:
i -> 2i
In that case, your mapping is from i to (1 << i) (the << is the bitwise left-shift operator).
System.out.println(
(1 << 2) + (1 << 4)
); // 20
Note that depending on what is it that you're trying to do, you may also consider using a java.util.BitSet instead.
BitSet demonstration
This may be completely off-the-mark, but assuming that you're doing some sort of interval arithmetics, then BitSet may be the data structure for you (see also on ideone.com):
import java.util.BitSet;
//...
static String interval(BitSet bs) {
int i = bs.nextSetBit(0);
int j = bs.nextClearBit(i);
return String.format("%02d:00-%02d:00", i, j);
}
public static void main(String[] args) {
BitSet workTime = new BitSet();
workTime.set(9, 17);
System.out.println(interval(workTime));
// 09:00-17:00
BitSet stackOverflowTime = new BitSet();
stackOverflowTime.set(10, 20);
System.out.println(interval(stackOverflowTime));
// 10:00-20:00
BitSet busyTime = new BitSet();
busyTime.or(workTime);
busyTime.or(stackOverflowTime);
System.out.println(interval(busyTime));
// 09:00-20:00
}
Note that methods like nextSetBit and nextClearBit makes it easy to find empty/occupied time slots. You can also do intersect, or, and, etc.
This simple example only finds the first interval, but you can make this more sophisticated and do various arithmetics on non-contiguous time intervals.
Integer.toBinaryString(i)
Returns a string representation of the integer argument as anunsigned integer in base 2.
To compute the length of the time-interval, you have to do
int totalrange = endtime - starttime;
Perhaps this is what you're looking for:
int startTime = 2;
int endTime = 24;
int range = endTime - startTime;
System.out.println(range + " can be expressed as the following sum:");
for (int size = 1; range > 0; size <<= 1, range >>= 1)
if ((range & 1) != 0)
System.out.format("+ %02d:00%n", size);
Output:
22 can be expressed as the following sum:
+ 02:00
+ 04:00
+ 16:00

Categories

Resources