How to display time amount to user? - java

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);

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;

Java doing Math not as expected [duplicate]

This question already has answers here:
Why double width = 50/110000; the output is 0.000000000000000?
(3 answers)
Closed 9 years ago.
I have this really weird problem with Java. Basicly, this is what is going on:
int i = (int) Math.ceil((30 * 50) / 1000);
which would be the same as
int i = (int) Math.ceil(1.5);
but it doesn't return 2, it returns 1! However, the seccond line does return 2! This is really weird...
If it helps, here's the actual line of code:
pStats.setPlayerEnergy(
player,
pStats.getPlayerEnergy(player)
+ (int) Math.ceil((pStats.getPlayerFoodTick(player) * pStats
.getPlayerHydrationTick(player)) / 1000));
Does anyone have an idea what's going on here and how to fix it?
This is Integer division. In Java:
(30 * 50) / 1000 = 1
int i = (int) Math.ceil((30.0 * 50) / 1000);
Will give you the expected result.
integer/integer will give you the integer value make any value either denominator or numerator as float you will get the answer
int i = (int) Math.ceil((30 * 50) / 1000.0);
or
int i = (int) Math.ceil((30.0 * 50) / 1000);
or
int i = (int) Math.ceil((30 * 50.0) / 1000);

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

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.

Categories