Generate specific intervals between two time/date in Java - java

I want to generate intervals between two given date/time.
For instance, say for 24 hour format (HH:MM), I have these two endpoints, 00:00 and 11:51, and suppose I want to partition it in 24 pieces. So my calculation is like this:
(hour * 3600 + min * 60) / 24
If I use calendar.add(Calendar.SECOND, (hour * 3600 + min * 60) / 24), I am getting wrong dates/time. My calculation is double and I think calendar.add() does not support double. Like it is taking 28.883 as 29.
In essence I want something like this:
now : 15:57
today start : 00:00 (24hh)
output : 00:00, 00:47.85, …, 15:57

The actual problem with your code is that you are performing integer division. I assume both hour and min are defined as integer types. The formula (hour * 3600 + min * 60) / 24 always yields an integer type. If you change the code to (hour * 3600 + min * 60) / 24d the expression yields a floating point value at least.
The next problem is indeed that Calendar.add(int field, int amount) accepts only an integer as second argument. Of course, if you are passing Calendar.SECOND as first argument, then your precision is not higher than seconds. You can use Calendar.MILLISECOND to get a higher precision.
However, I suggest using the new Java Date and Time API, instead of the troublesome old API:
LocalTime startTime = LocalTime.of(0, 0);
LocalTime endTime = LocalTime.of(11, 51);
long span = Duration.between(startTime, endTime).toNanos();
final int n = 23; // Number of pieces
LongStream.rangeClosed(0, n)
.map(i -> i * span / n)
.mapToObj(i -> startTime.plusNanos(i))
.forEach(System.out::println);

You need to save your start date in a calendar object and then when you generate each division use the formula:
startCalendar.add(Calendar.Second, count * (hour * 3600 + min * 60) / 24))
That way the arithmetic errors that you get by dividing by 24 (or whatever) are not accumulated.

Here’s a variant of MC Emperor’s fine code. I wanted to leave the math to the library class. Duration has methods dividedBy and multipliedBy that we can use to our advantage.
LocalTime startTime = LocalTime.of(0, 0);
LocalTime endTime = LocalTime.of(11, 51);
final int n = 24; // Number of pieces
Duration piece = Duration.between(startTime, endTime).dividedBy(n);
LocalTime[] partitionTimes = IntStream.rangeClosed(0, n)
.mapToObj(i -> startTime.plus(piece.multipliedBy(i)))
.toArray(LocalTime[]::new);
System.out.println(Arrays.toString(partitionTimes));
Output:
[00:00, 00:29:37.500, 00:59:15, 01:28:52.500, 01:58:30, 02:28:07.500,
02:57:45, 03:27:22.500, 03:57, 04:26:37.500, 04:56:15, 05:25:52.500,
05:55:30, 06:25:07.500, 06:54:45, 07:24:22.500, 07:54, 08:23:37.500,
08:53:15, 09:22:52.500, 09:52:30, 10:22:07.500, 10:51:45,
11:21:22.500, 11:51]
Is there a rounding problem? With a start time in whole minutes and 24 pieces there won’t be since 24 divides evenly into the number of nanoseconds in a minute. With another number of pieces you may decide whether the slight inaccuracy is worth worrying about. If it is, for each partitioning time multiply before you divide.

Related

how to get number of micro seconds in a day

I want to get the number of micro seconds in a day
so I tried as per below
long microDay = 24 * 60 * 60 * 1000 * 1000;
for which I am expecting value as 86400000000 but when I print it
System.out.println(microDay);
The value is 500654080
After spending 3 hours and breaking my head to know the reason,final I found that java think 24,60 and 1000 as int values and int*int =int but the maximum value of int is 2147483647 so it cant store 86400000000 and hence it the output is 500654080 (but I am not sure)
In the second case I wanted to calculate miliseconds in a day and the formula goes like this
long miliDay = 24 * 60 * 60 * 1000;
System.out.println(miliDay );
output 86400000
now when I did
System.out.println(microDay/ miliDay);
output 5
but when I tried this in a calculator 500654080/86400000= 5.794607407407407
why there is different in result?
You're performing 32-bit integer arithmetic, as every operand in 24 * 60 * 60 * 1000 * 1000 is an int... but the result is bigger than Integer.MAX_VALUE, so it's overflowing (just as you suspected). (This is actually happening at compile-time in this case, because it's a compile-time constant, but the effect is the same as if it happened at execution time.)
Effectively, each operation is truncated to 32 bits. As it happens, only the final multiplication by 1000 takes the result over 231 - 86400000 is fine.
86400000000 in binary is:
1010000011101110101110110000000000000
^
\- Bit 33
So after overflow, we just chop any leading bits until we've got 32:
00011101110101110110000000000000
And that value is 500654080.
Just use long instead, e.g.
long microDay = 24L * 60L * 60L * 1000L * 1000L;
(You definitely don't need all those constants to be of type long, but being consistent means it's obvious that all the operations will be performed using 64-bit arithmetic, with no need to consider associativity etc.)
A better approach, however, would be to use TimeUnit:
long microDay = TimeUnit.DAYS.toMicroseconds(1);
As for the division part, you're performing integer division - so the result is the integer part, rounded towards 0. If you want floating point arithmetic, you need to cast one of the operands to float or double... although if you start off with the right values, of course, you should get an exact integer anyway (1000).
For the first part, put a "L" at the end of one (or more) of the constants and Java will then use long arithmetic. e.g.
long microDay = 24L * 60 * 60 * 1000 * 1000;
Addendum: Why did you get 500654080?
86400000000 decimal = 141DD76000 hex.
But, the integer only holds 32 bits, which is 8 "digits". So you lose the leading 14 and retain 1DD76000 hex.
Converting that to decimal gives 500654080.
As for the division, when you divide ints by ints (or longs by longs) Java returns the result as an int or long, so it has to truncate (or round, but Java chose to truncate) the result to 5 instead of 5.7946... Force it to do floating point arithmetic by casting one of the values to a double, e.g.
System.out.println((double)microDay/ miliDay);
When you are performing a division between 2 integers, the results are an integer. The results of the arithmetic operation will be rounded down to the nearest integer.
int i = 5 / 2; // 2.5 is rounded down to 2
if you want the output to include the decimal precision, you will need to use a different primitive data type and explicitly specify your operands to be doubles.
double j = 5 / 2; //2.0 as 5 / 2 yields and integer 2 which will be casted to a double
double j = 5 / 2.0; //2.5 explicit usage of a double will tell the compiler to return the results in double
The nuclear operations inside
long microDay = 24 * 60 * 60 * 1000 * 1000;
are all Integers specific. Max value of Integer object is 2147483647. Which exceeds the original output which is long.
Simply specifying long to variable doesn't mean all operations using [ * ] will be done using long instances. All operations done in assignment became sort of truncated.
Solution is to explicitly specify that all nuclear operations should happen over long instance and not int instances.
long microDay = 24L * 60L * 60L * 1000L * 1000L;

Positive division, negative result in Java

I'm really puzzled by this. I'm dividing two positive numbers and getting a negative result (I'm using Java).
long hour = 92233720368L / (3600 * 1000000 );
I got as result -132.
But if I divide them as two long numbers, I get the right result:
long hour1 = 92233720368L / (3600000000L );
Then I get as result: 25
I'm wondering why it occurs...
Thank you in advance! :)
You must add L at the end of 3600 or 1000000:
Example:
long hour = 92233720368L / (3600 * 1000000L );
Here's what's hapenning:
System.out.println(3600 * 1000000); // Gives -694967296 because it exceeds the max limit of an integer size. So 92233720368L / -694967296 = -132
That's exactly what's happening in your division, the dominator is an integer and is considered as negative number for the reason I stated above. So in order to consider the multiplication result of type long you should add L after 3600 or after 1000000
It interprets 3600 and 10000000 as type int which cannot hold enough information to represent their product, and so you get a different number. You'd have to declare them both as type long to get the correct result.

Java converting seconds to year day hours minute seconds

I have a problem regarding really big numbers in Java.
I'm currently trying to convert a double consisting of a large number of seconds into years, days, hours, minutes and the seconds that are left.
My code looks like this: `
import java.util.Scanner;
public class timer {
public static void main(String[] args){
double sum = 1.1078087563769418E16;
double sec=0;
double min=0;
double hou=0;
double da=0;
double yea=0;
yea=sum/31536000;
int year = (int) yea;
sum=sum-year*31536000;
da=sum/86400;
int day = (int) da;
sum=sum-day*86400;
hou=sum/3600;
int hour = (int) hou;
sum=sum-hour*3600;
min=sum/60;
int minute = (int) min;
sum=sum-minute*60;
sec=sum;
int second = (int) sec;
sum=sum-second*60;
System.out.println(year+" "+day+" "+hour+" "+minute+" "+second);
}
}
`
When the double "sum" is as large as it is, the output gets weird. For example, the double "day" becomes larger than 365, which should be impossible.
Any solutions?
You are facing with a very common problem that most developers should know about: Integer overflow.
Your year variable is an int, the constant for second->year conversion is constant int, so int*int is... int. Except if your year is larger than approx 68, the result cannot fit into an int. Hence - overflow and silly results.
You have a couple of options available to you:
Do your timestamp arithmetic in longs. Really, that's the industry standard anyway.
If you insist on precision of over microseconds (or nano if you're concerned with last century only) - BigDecimal or BigInteger are your friends.
Use the TimeUnit class from concurrent package. It doesn't have years, but does have days and does conversion nicely (JodaTime would be even nicer though)
Overflow on the calculation sum=sum-year*31536000;
year and 31536000 are both integers, and their product is ~1E16, which is larger than java's max integer size. Use sum = sum-year*31536000.0 instead.
As a demonstration, add this code after you compute year:
System.out.println(year * 31536000.0); // 1.1078087556672E16
System.out.println(year * 31536000); // 1100687872
You can use java.math.BigDecimal class if you need to represent numbers with great precision.
If you need huge integers you can use java.math.BigInteger.
First use long not double then try this logic
long min = sum / (60) % 60;
long hou = sum / (60 * 60 )% 24;
long da = sum/(60*60*24)%30;
long yea = sum/(60*60*24*30)%365;
If that number is beyond the limit of long then use BigInteger but then this calculation will not work.

Assigning a value for each day for the past 2 weeks using 14 buckets to store them

This is kind of hard to explain but I need to come up with an algorithm that will use these 14 value buckets to move through it based on the day and assign them to these buckets..
For example, if started today (monday), value would go to bucket #1, for sunday it would be #7, sunday after #14 and the next day, on monday, it would use the #1 bucket again..
Any help appreciated.
Count the days and use modulo:
int bucket = (days % 14) + 1
If you start at 0; you can leave out the +1.
Calculating the day:
long start = ...
long current = System.currentTimeMillis();
int bucket = (int) ( ((start - current) / (1000 * 60 * 60 * 24)) % 14 )

Rounding a double

Hey guys, I am trying to round to 3 decimal places.
I used the following code.
this.hours = Round(hours + (mins / 60), 3);
But it's not working.
Where have I gone wrong?
Thanks
You can use this function:
public static double Round(double number, int decimals)
{
double mod = Math.pow(10.0, decimals);
return Math.round(number * mod ) / mod;
}
First thing is that all your variables are int so the result of your division is also an int, so nothing to Round.
Then take a look to: How to round a number to n decimal places in Java
If mins is an integer, then mins / 60 will result in an integer division, which always results in 0.
Try changing from 60 to 60.0 to make sure that the division is treated as a floating point division.
Example:
int hours = 5;
int mins = 7;
// This gives 5.0
System.out.println(Math.round(1000 * (hours + (mins / 60 ))) / 1000.0);
// While this gives the correct value 5.117. (.0 was added)
System.out.println(Math.round(1000 * (hours + (mins / 60.0))) / 1000.0);
if mins is an integer you have to divide through 60.0 to get a floating number which you can round
try using like follow
this.hours = Round(hours + (((double)mins) / 60), 3);
You can't. Doubles don't have decimal places, because they are binary, not decimal. You can convert it to something that does have decimal places, i.e. a base-ten number, e.g. BigDecimal, and adjust the precision, or you can format it for output with the facilities of java.text, e.g. DecimalFormat, or the appropriate System.out.printf() string.

Categories