Can't get count down timer to have 100th of seconds - java

I have a count down timer that works fine except for I'm geting numbers that have more then 2 digits for the 100th of seconds. I'm creating 2 calendar objects, bgetting there time alue in milli secons, and subtracting it. code
long milsecs1= calendar1.getTimeInMillis();
long milsecs2 = calendar2.getTimeInMillis();
long diff = milsecs2 - milsecs1;
long dsecs = diff / 1000;
long ddays = diff / (24 * 60 * 60 * 1000);
diff=diff-ddays *(24 * 60 * 60 * 1000);
textDays.setText( Integer.toString( (int)ddays)+":" );
long dhours = diff / (60 * 60 * 1000);
diff=diff-dhours* (60 * 60 * 1000);
textHours.setText( Integer.toString( (int)dhours)+":" );
long dminutes = diff / (60 * 1000);
diff=diff-dminutes* (60 * 1000);
textMinuts.setText( Integer.toString( (int)dminutes)+":" );
/////////////////////////////////////////////////
// THIS IS THE PART THAT IS NOT WORKING, I WANT NUMBERS 0-99, BUT GETTING NUMBERS LIKE 230
long dseconds = diff / (100);
textSeconds.setText( Integer.toString( (int)dseconds)+":" );
diff=diff-dseconds;

Joda time provides a much simpler (and thoroughly proven) solution in its Period class. Something like this should do the trick (untested):
Period period = new Period(calendar1.getTimeInMillis(), calendar2.getTimeInMillis());
int days = period.getDays();
int hours = period.getHours();
... etc.

Related

Convert Days to hours:minutes:second java

How can I convert 0.230324074074074 to 05:31:40 in Java? I have code in sql but need in java.
(select * from(SELECT TRUNC (
( (X_GSA_LEAVE_SITE - X_GSA_ARRIVE_ONSITE)
* 24
* 60)
/ 60)
|| ':'
|| ( ( (X_GSA_LEAVE_SITE - X_GSA_ARRIVE_ONSITE)
* 24
* 60)
- TRUNC (
( ( X_GSA_LEAVE_SITE
- X_GSA_ARRIVE_ONSITE)
* 24
* 60)
/ 60)
* 60)
It appears that the value 0.230324 is a fraction of a day, and you want to display this as hours:minutes:seconds. There is a fairly straightforward way to do this in Java 8:
double input = 0.230324074074074d;
long seconds = new Double(input*24*60*60).longValue();
System.out.println(LocalTime.MIN.plusSeconds(seconds)
.format(DateTimeFormatter.ISO_LOCAL_TIME));
05:31:39
Demo
You can convert that fraction of day to a LocalTime using:
LocalTime.ofSecondOfDay((long)(0.230324074074074 * 24 * 60 * 60))
This converts the value to seconds and constructs a LocalTime object. Printing the result outputs "05:31:39" (LocalTime.toString outputs time in your desired format). You may need to control rounding in a different way if you expect exactly 05:31:40)
Just for fun here is an old fashioned Calendar version
int seconds = (int) (0.230324074074074 * 24 * 60 * 60);
Calendar cal = Calendar.getInstance();
cal.set(Calendar.HOUR, 0);
cal.set(Calendar.MINUTE, 0);
cal.set(Calendar.SECOND, 0);
cal.add(Calendar.SECOND, seconds);
String result = String.format("%02d:%02d:%02d",
cal.get(Calendar.HOUR),
cal.get(Calendar.MINUTE),
cal.get(Calendar.SECOND));
System.out.println(result);
long seconds = (long) (0.230324074074074 * 24 * 60 * 60);
String result = String.format("%02d:%02d:%02d", seconds / 3600, (seconds % 3600) / 60, (seconds % 60));
System.out.println(result);

getTimeinMillis returns a negative value

I am making an app which can show time left to some date, and an elapsed time after some date. But I endure some difficulties with dates less than 1970 and bigger than 3300. I have found an explanation why it happens.
The problem is this sentence from getTimeInMillis:
the current time as UTC milliseconds from the epoch.
And, as far as i remember, the epoch started on January 1st 1970 you get a negative number for anything before that.
My question is how to solve this problem. (And yes i have heard about JodaTime, I am not allowed to use this library in this app.)
What default(standard) tools should i use?
Here it is a piece of code that does not work properly.
private void getDateTime()
{
Date date = new Date();
timeRemaining = Calendar.getInstance();
date.setTime(timeRemaining.getTimeInMillis());
millis = Math.abs(timeRemaining.getTimeInMillis() - targetDate.getTimeInMillis());
int scnds = (int) (millis / 1000) % 60 ;
int mnts = (int) ((millis / (1000 * 60)) % 60);
int hrs = (int) ((millis / (1000 * 60 * 60)) % 24);
int dys = (int) (millis / (1000 * 60 * 60 * 24));
resultDate.setText(getString(R.string.formating, dys, hrs, mnts, scnds));
}
You can achieve this by leveraging the Duration and LocalDateTime class(es) introduced in Java 8 --
import java.time.Duration;
import java.time.LocalDateTime;
class Main {
public static void main(String[] args) {
LocalDateTime fromDateTime = LocalDateTime.of(1914, 9, 10, 0, 0, 0);
LocalDateTime toDateTime = LocalDateTime.of(2014, 12, 16, 0, 0, 0);
System.out.println(Duration.between(fromDateTime, toDateTime).toMillis());
}
}

Calculating elapsed time using delta

I must be making some silly mistake in my code, In my head this should work but the timer works a bit too fast ( I want to get time left in seconds).
My code:
timeElapsed = 0;
timeLeft = 60;
//delta = time it took to get through one frame (60 fps).
timeElapsed += delta/getFramesPerSecond(); //FPS = 60f
timeLeft -= timeElapsed; //timeLeft starts at 60 (seconds)
timeDisplay = "Time left: " + timeLeft;
I have checked that FPS is always 60, what am I missing here?
Delta sample prints:
0.016969847
0.017038532
0.017123796
0.017026689
0.016969848
0.017059453
0.01697774
0.016987609
0.017073665
0.017035767
0.01708432
timeElapsed+timeLeft should be a constant (thus both should change by the same amount in opposite directions), however, you are repeatedly reducing timeLeft by timeElapsed
In a demonstrative example with steps 1 in timeElapsed, your code gives
timeElapsed timeLeft
0 60
1 59
2 57
3 54
4 50
5 45
6 39
7 32
Change the code to
timeDelta = delta/getFramesPerSecond();
timeElapsed += timeDelta;
timeLeft -= timeDelta;
timeDisplay = "Time left: " + timeLeft;

How to multiply longs within a drool

I would like to write one line of code to calculate the number of milliseconds in 30 days.
long gracePeriod = 30/*days*/ * 24 * 60 * 60 * 1000;
However, in the drool that will not work because it is assigning an int to a long. So I figured I could do something like this.
long gracePeriod = 30l/*days*/ * 24l * 60l * 60l * 1000l;
But, that also will not work so I had to do something dumb like:
long grace1 = 30;
long grace2 = 24;
long grace3 = 60;
long grace4 = 1000;
long grace = grace1 * grace2 * grace3 * grace3 * grace4;
Is there any way to make this simpler.
For me, all 4 of these samples work (and are cleaner than what you had to resort to). If one or many isn't working for you, it's probably either a problem with your IDE or Java environment. If so, let us know what java version you're running and the environment.
public class TempProject
{
public static void main(String args[])
{
long gracePeriod = 30l /*days*/ * 24l * 60l * 60l * 1000l;
long gracePeriod2 = 30l /*days*/ * 24 * 60 * 60 * 1000;
long gracePeriod3 = ((long)30) /*days*/ * 24 * 60 * 60 * 1000;
long gracePeriod4 = ((long) 30)/*days*/ * ((long) 24) * ((long) 60) * ((long) 60) * ((long) 1000);
System.out.println(gracePeriod);
System.out.println(gracePeriod2);
System.out.println(gracePeriod3);
System.out.println(gracePeriod4);
}
}
Of course the easiest way is to hardcode the number ;)
long gracePeriod = 2592000000l;

How to display time amount to user?

I want to convert time amount from milli-sec to a human readable string.
For example:
3,600,000 should be displayed as 1:00:00 (1 hour).
Is there an existing library or class in Java that can do that?
Since 1.5 there is the java.util.concurrent.TimeUnit class, use it like this:
String.format("%d min, %d sec",
TimeUnit.MILLISECONDS.toMinutes(millis),
TimeUnit.MILLISECONDS.toSeconds(millis) -
TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(millis))
);
For Versions below 1.5 You have to use
int seconds = (int) (milliseconds / 1000) % 60 ;
int minutes = (int) ((milliseconds / (1000*60)) % 60);
int hours = (int) ((milliseconds / (1000*60*60)) % 24);

Categories