Big long numerics dividing with round - java

I have problem with java then i want to divade big long type numerics for example if i divide 165600139 / 86400000 = 1.9, but my method return 1 without rounding :/
public static long calcDaysBefore(Date date) {
int MILISECONDS_IN_DAY = 24 * 60 * 60 * 1000;
long days = 0;
if (date != null) {
long current = getCurrentDate().getTime() - date.getTime();
days = current / MILISECONDS_IN_DAY;
}
return days;
}

It is rounding down and is similar to doing
days = Math.floor((double) current / MILISECONDS_IN_DAY);
If you want to round half up you can write
days = (current + MILISECONDS_IN_DAY/2) / MILISECONDS_IN_DAY;
Using floating point you could use the following which is much slower.
days = Math.round((double) current / MILISECONDS_IN_DAY);
if you want to round up you can do
days = (current + MILISECONDS_IN_DAY-1) / MILISECONDS_IN_DAY;
or
days = Math.ceil((double) current / MILISECONDS_IN_DAY);
btw milli-seconds has two l's

actually the result is rounded, there are several rounding modes, see http://docs.oracle.com/javase/1.5.0/docs/api/java/math/RoundingMode.html, in your case you are getting the number of full days. For rounding to the closest long we can use
long days = Math.round(current / 8640000.0);

cast to double.
days = (double)current / (double)MILISECONDS_IN_DAY;

Related

Java remove millisecond precision from long value

so from this :
1459245759880
to this
1459245759000
Usual integer rounding?
long millis = 1459245759880L;
long rounded = millis / 1000 * 1000;
Using Java time (convenient if you need to do date/time operations on the result - in that case you can work with the instant):
Instant i = Instant.ofEpochMilli(millis).truncatedTo(ChronoUnit.SECONDS);
long rounded = i.toEpochMilli();
More convoluted (and probably not very clear):
long rounded = 1000 * TimeUnit.SECONDS.convert(millis, TimeUnit.MILLISECONDS);
//OR
long rounded = TimeUnit.MILLISECONDS.convert(TimeUnit.SECONDS.convert(millis, TimeUnit.MILLISECONDS), TimeUnit.SECONDS);
long x = 1459245759880;
long y = x - (x % 1000);
Use simply the modulo operator to get reminder and then subtract it from the actual value.
Why not this
long value = 1459245759880L;
System.out.println(1000 * (value / 1000));

Java How to get the difference between currentMillis and a timestamp in the past in seconds

Lets say i have long currentMillis and long oldMillis. The difference between the two timestamps is very tiny and always less than 1 second.
If i want to know the difference between the timestamps in milleseconds, i can do the following:
long difference = currentmillis-oldmillis;
And if i want to convert difference to seconds, i can just divide it by 1000. However if the difference in milliseconds is less than 1000 milliseconds(<1 second), dividing it by 1000 will result in 0.
How can i get the difference between the two timestamps if the difference is less than a second? For example, if the difference is 500 milliseconds, the desired output is 0.5 seconds.
Using float/double instead of long always returns 0.0 for some reason i don't understand.
My code:
private long oldmillis = 0, difference = 0;
private long calculateDifference()
{
long currentMillis = System.currentTimeMillis();
if (oldMillis == 0) oldMillis = currentMillis;
difference = currentMillis - oldMillis;
oldMillis = currentMillis;
return difference;
}
The method calculateDifference is called randomly with a small random time interval.
It sounds like you just need to convert the results into double before the division:
// This will work
double differenceMillis = currentMillis - oldMillis;
double differenceSeconds = differenceMillis / 1000;
// This will *not* work
double differenceSecondsBroken = (currentMillis - oldMillis) / 1000;
In the latter code, the division is performed using integer arithmetic, so you'll end up with a result of 0 that is then converted to a double.
An alternative which would work is to divide by 1000.0, which would force the arithmetic to be done using floating point:
double differenceSeconds = (currentMillis - oldMillis) / 1000.0;

Date calculation - progressbar showing timeleft

i want to make a simple progressbar showing me how much time some process takes. At the moment of creation of it I have only actual percentage (as int) and time that is left(as String formatted HH:mm:ss). I want it to update every second and show me the actual state of process. I've tried everything and it doesn't work. Current version looks like this - tell me please what I'm doing wrong...
int initialProgress = 35; // %
// time to finish process
Date endDate = new SimpleDateFormat("HH:mm:ss").parse("07:07:07");
Date now = new Date();
long totalDuration = (long) (((double)(endDate.getTimeInMillis()
- now.getTimeInMillis()) * 100.0 / (double)initialProgress);
and then every second I repeat:
now = new Date();
int currentProgress = (totalDuration - endDate.getTimeInMillis()
+ now.getTimeInMillis())/totalDuration;
It simply is not working. Total duration is even something strange...
The issue seems to be that you have a time remaining String and you want to parse it to percentage of work done.
The first thing you need, obviously, is the total expected time. Lets assume that this is also a String.
First write a method for parsing your HH:mm:ss String to a long representing time remaining in seconds.
public long parseToSeconds(final String duration) throws ParseException {
final MessageFormat durationFormat = new MessageFormat("{0,number,#}:{1,number,#}:{2,number,#}");
final Object[] parsedTimeRemaining = durationFormat.parse(duration);
final long totalDuration = TimeUnit.HOURS.toSeconds((Long) parsedTimeRemaining[0])
+ TimeUnit.MINUTES.toSeconds((Long) parsedTimeRemaining[1])
+ (Long) parsedTimeRemaining[2];
return totalDuration;
}
What we do here is use a MessageFormat to parse your String into an array of Object. As we have told the MessageFormat that these are numbers, it will automagically convert (or try to convert, hence the exception) to Long.
Once we have those numbers we scale them all to seconds using the (very useful) TimeUnit class.
A couple of quick tests to ensure we're on the right track:
System.out.println(parseToSeconds("00:00:01"));
System.out.println(parseToSeconds("00:01:00"));
System.out.println(parseToSeconds("01:00:00"));
System.out.println(parseToSeconds("01:01:01"));
Output:
1
60
3600
3661
Looks good.
Lets assume that right as the start of the process we get a time remaining, for simplicity, of "04:04:04", this gives 14644. Now we just need to store that and calculate the percentage against any new duration String. This should do the trick:
public int asPercentage(final long totalTime, final long remaining) {
final double percentage = remaining / ((double) totalTime);
return (int) (percentage * 100);
}
Note the fact that I cast (seemingly pointlessly) one of the items to a double. This is because in Java any operation on an integral type always returns another integral type. Casting to a double forces it to return a double.
Lets do a quick check again:
final long totalDuration = 14644;
System.out.println(asPercentage(totalDuration, parseToSeconds("03:03:03")));
System.out.println(asPercentage(totalDuration, parseToSeconds("02:02:02")));
System.out.println(asPercentage(totalDuration, parseToSeconds("01:01:01")));
Output:
75
50
25
Looks good, that is the time remaining as a percentage of the total. Maybe to quite what we want for a progress bar. Lets invert it:
public static int asPercentage(final long totalTime, final long remaining) {
final double percentage = remaining / ((double) totalTime);
return 100 - (int) (percentage * 100);
}
Output:
25
50
75
Ah-ha. Much better.

Difference between two dates and percentage of current time java

I'm trying to make a timing mechanism using threads, and I'm having a problem in getting the time difference between two Dates, and using that difference to get a current percentage of the time left. Here is the concept I'm trying to prototype:
And here is my implementation:
long startMilisecs = System.currentTimeMillis();
long currentMilisecs;
long endDateMilisecs = getEndDate().getTime();
int diffMillisecs = ((int)(endDateMilisecs - startMilisecs) / 1000) / 60;
int currPerc;
while (startMilisecs <= endDateMilisecs)
{
currentMilisecs = (int) System.currentTimeMillis();
currPerc = ((int)currentMilisecs * 100) / diffMillisecs;
System.out.println(" Current Percentage: " + currPerc);
}
The problem with this code is that the percentage is not starting from 0 but rather in the 20's to 40 percent.
Can you tell me what is wrong with this? and for this problem I have been restricted to using only threads.
check below:
public static int getPercentageLeft(Date start, Date end) {
long now = System.currentTimeMillis();
long s = start.getTime();
long e = end.getTime();
if (s >= e || now >= e) {
return 0;
}
if (now <= s) {
return 100;
}
return (int) ((e - now) * 100 / (e - s));
}
You need to subtract the starting time like this
currPerc = ((currentMilisecs - startMilisecs) * 100) / diffMillisecs;
to get the correct percentage.
The problem is with the System.currentTimeMillis();. Taken from the javadoc:
public static long currentTimeMillis()
Returns the current time in milliseconds. Note that while the unit of
time of the return value is a millisecond, the granularity of the
value depends on the underlying operating system and may be larger.
For example, many operating systems measure time in units of tens of
milliseconds.
See the description of the class Date for a discussion of slight
discrepancies that may arise between "computer time" and coordinated
universal time (UTC).
Returns:
the difference, measured in milliseconds, between the current time and midnight, January 1, 1970 UTC.
So your current time in milliseconds is based on January 1, 1970 UTC, not on your start date.
You need to calculate current time by subtracting start time from the value that is given by System.currentTimeMillis();.
I am basically formulating your linked image here. Other alternative calculations can also be carried out.

Calculating difference in two time

I am calculating the difference between two times and i am able to get the difference in hours and minuted using separate equations,is there any single equation from which i can get hours and minutes at one go.I am using like:
here diff is the difference between two time value
long diffHours1 = diff / (60 * 60 * 1000);
long min=diff/(60*1000);
I'm not sure it is helpful here, but Joda Time seems to have a little more verbose solution using Period e.g.
Period p = new Period(startDate, endDate)
int minutes = p.getMinutes(); //returns the left over minutes part
int seconds = p.getSeconds(); //returns the seconds part
I'm not sure that for this particular case you need something else than what you have, I agree with aix's
is there any single equation from which i can get hours and minutes at one go
No, not easily. A Java expression can only have one result; returning several things is not impossible, but would require additional machinery (a wrapper class, a tuple etc). This would result in code that's significantly more complicated than what you have right now.
What you can do to simplify things a little bit is compute minutes first, and then compute hours based on minutes:
long diffMinutes = diff / (60*1000);
long diffHours = diffMinutes / 60;
Yes there is:
String oneGo = (diff / (60 * 60 * 1000)) + " " + (diff / (60 * 1000));
:-)
Well, two equations are not that bad (actually using more lines makes it easier to read), although you might change the order, correct the equation and cache some results.
diff = //time difference in milliseconds
long diffInMinutes = diff / (60 * 1000);
//get the number of hours, e.g. 140 / 60 = 2
long hours = diffInMinutes / 60;
//get the left over minutes, e.g. 140 % 60 = 20
long minutes = diffInMinutes % 60;
If the reason you want one equation is ease of use, try using an alternative library like Joda Time.

Categories

Resources