How to gain milliseconds of LocalTime variable? [duplicate] - java

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.

Related

Calculate number of milliseconds between two times

I'm trying to calculate how many milliseconds between two times (for example between 13:00 to 13:01 there are 60000 milliseconds).
The times are represented by 2 integers (hour, minute).
I wrote this function:
public static long millisBetweenTimes(int h1, int m1, int h2, int m2) { //hour1, minute1, hour2, minute2
long millis;
millis = (h2 - h1) * (60 * 60000);
if (m < tm)
millis += (m2 - m1) * 60000;
else
millis -= (m1 - m2) * 60000;
return millis;
}
However, this won't work when the second time is the day after (e.g. how many milliseconds between 14:00 Sunday to 13:00 Monday?)
As Robby already said in the comments, you should use classes from the java.time package. With the classes LocalTime and Duration, you could get the milliseconds between two points in time.
LocalTime t0 = LocalTime.of(14, 0);
LocalTime t1 = LocalTime.of(13, 0);
Duration d = Duration.between(t0, t1);
if (d.isNegative()) {
d = d.plusDays(1);
}
System.out.println(d.toMillis());
A Duration is a, well, duration: the amount of time between two points in time. If the second time lies before the first, then the duration is negative. In such case, we need to add 1 day to the duration.
Now we have an amount of time represented by the Duration class. This class contains many methods to convert it to a certain time unit. In our case, toMillis() is exactly what we need.
Online demo
Instead of d.isNegative(), you can also use t1.isBefore(t0), if you think it's more expressive.
Note: I think this is not as half as clumsy as doing the math yourself.
Your approach would only work in a single 24 hour cycle as you are passing in two hour integers and subtracting them. So if you are calculating the amount of milliseconds from 13:00 to 14:00 tomorrow the second time input needs to be 25:00 as 24 hours have passed. Another way you can approach this is by using java dates and taking out the hour from the day you want to start and finish.

Convert int to time and add two times in 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.

Java how to compare LocalTime using only hours, minutes and seconds

I want to compare if 2 LocalTime are equal, but only using the hours, minutes and seconds, not with all the data of the variable, like milliseconds.
How can I accomplish that?
Considering the last edited version of your question, you can compare two instances of LocalTime by just hour, minute and second part this way:
LocalTime lt1 = LocalTime.now(); // usually contains seconds and subseconds
LocalTime lt2 = LocalTime.of(22, 48); // example with zero second part
boolean isEqualInSecondPrecision =
lt1.truncatedTo(ChronoUnit.SECONDS).equals(lt2.truncatedTo(ChronoUnit.SECONDS));
You can set the hours to the same in both with myTime.withHour(0), than you have left only the minutes and seconds that differ and you are able to come these 2 times.
Example:
time1 = ...
time2 = ...
if (time1.withHour(0).equals(time2.withHour(0))) {
System.out.println('Minutes and Seconds of time1 and time2 are equal!');
}
You can just set both nanos to one number to make them the same with each other, say, zero, to compare them.
LocalTime localTime1 = LocalTime.of(1, 2, 3, 100);
LocalTime localTime2 = LocalTime.of(1, 2, 3, 47);
if (localTime1.withNano(0).equals(localTime2.withNano(0))){
System.out.println("something");
}
Something like this
LocalTime t1=..
LocalTime t2=..
LocalTime.of(t1.getHour(), t1.getMinutes()).compareTo(LocalTime.of(t2.getHour(),t2.getMinutes());
with also seconds if u need of course

Time conversion [duplicate]

This question already has answers here:
Java: Converting an input of seconds into hours/minutes/seconds
(2 answers)
Closed 6 years ago.
How to convert from duration (in minutes) to hour and minutes?
For example: hour = 8 and minute = 25. Now person enter duration (in minutes) 60 for example. Now how to show time 9:25 because duration was 60 minutes?
You can use LocalTime provided in java.time.
LocalTime time = LocalTime.of(8, 25).plusMinutes(60);
System.out.println(time);
all date/time values in Java are internally in milliseconds. So multiply by the right factor to get milliseconds (60000 for minutes, 3600000 for hours). this can be added or subtracted from a date.
function addMinutes(startDate, minutes) {
var millis = startDate.getTime();
return new Date(millis + minutes*60000);
}
function addHours(startDate, hours) {
var millis = startDate.getTime();
return new Date(millis + hours*3600000);
}

How to create a joda time duration from java.sql.Time?

Hello I have this excerpt of code:
end = new DateTime(mergeToDateTime(this.endDate, this.empEndTime));
Duration extraTime = new Duration(this.preTime.getTime()); //add the first 30 mins
extraTime = extraTime.plus(new Duration(this.postTime.getTime())); //add the second 30 mins
end = end.plus(extraTime); // extraTime = -3600?
When I look in the debugger my durations are always coming up negative. I have no idea why this is, even though according to the API, it is possible to create a duration out of the a long type, hence the getTime(). (preTime and postTime are java.sql.Time types)
I guess your instances of java.sql.Time were created in such a way that their millisecond values include timezone offset.
For example, deprecated java.sql.Time(int hour, int minute, int second) constructor takes offset of the current timezone into account:
System.out.println(new Time(1, 0, 0).getTime()); // Prints -7200000 in UTC+3 timezone
It looks like timezone offset is introduced by JDBC driver, and it can be easily compensated by converting java.sql.Time to LocalTime (and vice versa):
LocalTime lt = new LocalTime(time);
Then you can convert LocalTime to duration:
Duration d = new Duration(lt.getMillisOfDay());
Aren't you starting out wrong when you use an instant in time as duration? The constructor signature you are using is Duration(long duration), not Duration(long startInstant) -- there is no such constructor, in fact.

Categories