Convert int to time and add two times in java - java

I am trying to get the duration of a reservation and convert it to time so that I can update the end time of the reservation. Say the user enters the start time as 18:05:00 and the total duration is 15 (which is the total minutes for reservation), I would wanna convert 15 into minutes say 00:15:00 and wanna get the result as 18:25:00.
Is there a way to do so?

Note that 15 minutes after 18:05 is 18:20, not 18:25.
You can use the LocalTime class to store your time, and add n minutes to it.
LocalTime originalTime = LocalTime.parse("18:05:00");
int minutes = 15; // replace this with the user input
LocalTime newTime = originalTime.plusMinutes(minutes)
System.out.println(newTime);
To store "15 minutes", you can use the Duration class.

Related

Duration of minutes not working correctly in Java/Android

I am trying to display a rest time value in hours and minutes to my UI on an application I am finishing up.. I made use of another StackOverflow forum to figure this out and so far it is working okay, the time is displaying, but I think the maths is wrong somewhere..
I have two TextViews, one which displays active time in minutes, and another which displays rest time in hours and minutes (as the rest time will normally be a significantly longer period). The rest time is essentially 24hrs minus the active time.
So far, I have converted my stored active time string to an Int, subtracted that from the minute value for 24 hours (1440 minutes), then used the Duration method to convert that value to hours and minutes (hh:MM) which worked fine, the UI showed the correct subtracted value in hh:MM.
My problem is when I tried to split this into parts using a string, where my string is (restHours + " h" + restMinutes + " minutes") I get the hours and minutes value for the entire restTimeInt value (for example: 23h 1430minutes).
How can I change this so it displays the correct minutes value (for example: 23hr 40min)?
int activeTimeValue = Integer.parseInt(activityTime); // ex: 10 mins
int day = 1440;
int restTimeInt = day - activeTimeValue; // 1430 mins
Duration d = Duration.ofMinutes(restTimeInt);
int restHours = (int) d.toHours();
int restMinutes = (int) d.toMinutes();
restTimeTV.setText(restHours + " hr" + restMinutes + " mins");
Duration.minus() and Duration.toMinutesPart()
Now you’re at it, why not go all in on Duration and let it handle all math for you? With a little help it can even parse your string of minutes.
String activityTimeStr = "10"; // Minutes
Duration activityTime = Duration.parse("PT" + activityTimeStr + "M");
Duration restTime = Duration.ofDays(1).minus(activityTime);
System.out.format("Rest time: %s%n", restTime);
Output is:
Rest time: PT23H50M
So 23 hours 50 minutes, as expected. If you need those numbers, 23 and 50, for example for formatting for the user, as deHaar said, use the toMinutesPart method of Duration:
int restHours = Math.toIntExact(restTime.toHours());
int restMinutes = restTime.toMinutesPart();
System.out.format("Rest time: %d hours %d minutes%n", restHours, restMinutes);
Rest time: 23 hours 50 minutes

How can randomize a time between yesterday and today's local DateTime in java?

I need to randomize a time in java.
If now the time is 24/2/2021 13:56:13, then I need to randomize a time between 23/2/2021 13:56:13 and 24/2/2021 13:56:13. I am not familiar to random function in Java so that I maybe need some help. Thank you for your attention.
Take LocalDateTime.now() then go back in time with a random amount of seconds between 0 and 86400
int randomSeconds = new Random().nextInt(3600 * 24);
LocalDateTime anyTime = LocalDateTime.now().minusSeconds(randomSeconds);
System.out.println(anyTime);
General solution
Define the beginning dates and end of the period
Compute the difference in seconds and get a random int in that range
Compute the random date with one of these 2 ways:
Go from the beginning and add the random amount of seconds
Go from the end and remove the random amount of seconds
LocalDateTime periodStart = LocalDateTime.now().minusDays(1);
LocalDateTime periodEnd = LocalDateTime.now();
int randomSeconds = new Random().nextInt((int) periodStart.until(periodEnd, ChronoUnit.SECONDS));
//LocalDateTime anyTime = periodStart.plusSeconds(randomSeconds);
LocalDateTime anyTime = periodEnd.minusSeconds(randomSeconds);

How to gain milliseconds of LocalTime variable? [duplicate]

This question already has answers here:
How to get milliseconds from LocalDateTime in Java 8
(14 answers)
Closed 3 years ago.
Executed piece of code :
String lapTime = "27:10.190";
int minutes = Integer.parseInt(lapTime.substring(0, lapTime.indexOf(":")));
int seconds = Integer.parseInt(lapTime.substring(lapTime.indexOf(":")+1, lapTime.indexOf(".")));
int milliseconds = Integer.parseInt(lapTime.substring(lapTime.indexOf(".")+1));
LocalTime localTime = LocalTime.of(0, minutes, seconds, milliseconds);
How to gain number of milliseconds of LocalTime localTime = LocalTime.of(0, minutes, seconds, milliseconds); ?
TL;DR Use Duration, not LocalTime. See end of answer.
Question code is incorrect
Be aware that the 4th argument to LocalTime.of() is nanosecond, not millisecond, which you'd see if you print localTime:
System.out.println(localTime); // prints: 00:27:10.000000190
So you need to change your code to:
LocalTime localTime = LocalTime.of(0, minutes, seconds, milliseconds * 1000000);
System.out.println(localTime); // prints: 00:27:10.190
Using LocalTime
If you wanted the milliseconds value back, call getLong(TemporalField field) with ChronoField.MILLI_OF_SECOND:
localTime.getLong(ChronoField.MILLI_OF_SECOND) // returns 190
To gain total number of milliseconds, i.e. not just the milliseconds value, use ChronoField.MILLI_OF_DAY as argument:
localTime.getLong(ChronoField.MILLI_OF_DAY) // returns 1630190
Using Duration
However, since the input is named lapTime, the LocalTime class is not the right tool for the job. E.g. your code will fail if minutes >= 60.
The right tool is the Duration class, e.g.
Duration duration = Duration.ofMinutes(minutes).plusSeconds(seconds).plusMillis(milliseconds);
Or:
Duration duration = Duration.ofSeconds(seconds, milliseconds * 1000000).plusMinutes(minutes);
You can then get the milliseconds directly by calling toMillis():
duration.toMillis(); // returns 1630190
That works even if the lap time exceeds one hour, e.g.
String lapTime = "127:10.190";
. . .
duration.toMillis(); // returns 7630190
In Java 9+, you can get the millisecond part back easily, by calling toMillisPart():
duration.toMillisPart(); // returns 190
To get the number of milliseconds within the second, you can do localTime.get(ChronoField.MILLI_OF_SECOND).
You can do localTime.toNanoOfDay() / 1000000 to get the number of milliseconds since the start of the day.
Since a LocalTime has no day or date associated with it, you can't directly get milliseconds-since-the-epoch.
You can attach a LocalDate to a LocalTime using LocalTime.atDate to get a LocalDateTime. Then you can call atZone, atOffset or toInstant to get an object that can return epochMillis.

Loop through time difference logic

I am using Joda DateTime and have 2 dates :
DateTime old //which is 1:46PM
DateTime new //which is 6:46PM
note: excluded the dates.
How may i be able to loop through the difference in this order :
(print a message for the first half hour, another message for the next 30 minutes and another message per subsequent hour) ?
I was thinking of Subtracting the old date from the new date then make a loop but i don't get the logic. Any pointers will be helpful.
example
If i subtract both times above, i will have an elapsed time of 5 hours.
Loop 5 hours
{
for the first hour (print this)
next 30minutes (print that)
every subsequent hour (print ....)
}
I would use the type LocalTime instead. If you have DateTime as input then please convert it using the method toLocalTime() (with same time and chronology and timezone).
LocalTime start = new LocalTime(13, 46);
LocalTime end = new LocalTime(18, 46);
LocalTime current = start;
for (int i = 0; current.isBefore(end); i++) {
// code your print action here
current = current.plusMinutes((i < 2) ? 30 : 60);
}
Then you get an action for following times:
13:46
14:16
14:46
15:46
16:46
17:46

How do I add time to a timestamp?

I need to add 14 minutes and 59 seconds to an unknown time in an array. How do I do this? This is what I have so far:
Date duration = df.parse("0000-00-00 00:14:59");
arrayOpportunity[2] = arrayOpportunity[2] + duration;
The time is not being changed. Thanks!
I have done my research. I cant paste the entire code I have. But mainly I didnt want to make you read it all. Just looking for a simple answer of how to add two timestamps.
If you are talking about a java.sql.Timestamp, it has a method called setTime. java.util.Date has a setTime method as well for that sort of thing.
You could something like this:
static final Long duration = ((14 * 60) + 59) * 1000;
oldTimestamp.setTime(oldTimestamp.getTime() + duration);
If you want to add time in millis then you can just add
(((14 * 60) + 59) * 1000) <-- Mili second value of 14 m and 59 sec
If you just want to add times, I suggest using Joda Time.
The class LocalTime lets you add durations like this:
LocalTime timeSum = time.plusMinutes(14).plusSeconds(59);
Just add the appropriate number of milliseconds using #getTime() and #setTime():
timeStamp.setTime(timeStamp.getTime() + (((14 * 60) + 59)* 1000));
arrayOpportunity[2] = arrayOpportunity[2] + 14*60*1000 + 59*1000;
The Date object you have may work, but it doesn't really represent 14 minutes and 59 seconds, it just represents a particular time in calendar (eg. 14 minutes 59 after the epoch start which is 1st January 1970 00:14:59).

Categories