This question already exists:
how to calculate difference between two dates using java [duplicate]
Closed 7 years ago.
I need to know the difference between two java.sql.Time objects and the difference must be measured in minutes.
This is how I do it:
java.sql.Time srTime = sr.getTime(); // 12:40:04
java.sql.Time chTime = ch.getTime(); // 12:32:00
long diff = Math.abs(srTime.getTime() - chTime.getTime()); // 484000
The result (diff) is equal to 484000. How to make it equal to 8 minutes?
Use division
int result = 484000
/ 1000 /* take out milliseconds */
/ 60 /* convert to minutes */;
System.out.println(result);
Output:
8
You can simply divide it like this:
long diff = Math.abs(srTime.getTime() - chTime.getTime());
long res = diff/60000;
The diff which you are getting is in milliseconds, so you need to divide it by 60000 to get that in minutes.
If you are using java 1.7 you can use the TimeUnit object.
http://docs.oracle.com/javase/7/docs/api/java/util/concurrent/TimeUnit.html
Once you are getting a response um milliseconds, look at this example
long minutes = TimeUnit.MILLISECONDS.toMinutes(diff);
long seconds = TimeUnit.MILLISECONDS.toSeconds(diff);
Related
This question already has answers here:
How do I measure time elapsed in Java? [duplicate]
(15 answers)
In Java, how do I get the difference in seconds between 2 dates?
(13 answers)
How do I write a correct micro-benchmark in Java?
(11 answers)
Closed 2 years ago.
I am practically checking how much time taking by collection(s) insertion with 'N' elements,
Now I am stuck in checking total time taken by ArrayList in Insertion process.
Timestamp startTimeStamp = new Timestamp(System.currentTimeMillis());
System.out.println("Start Insertion :: "+startTimeStamp);
List<Integer> intList = new ArrayList<>();
for (int i = 0; i <= 100000000; i++) {
intList.add(i);
}
Timestamp endTimeStamp = new Timestamp(System.currentTimeMillis());
System.out.println("End insertion :: "+endTimeStamp);
// Total time taken
// TODO
Output :
Start Insertion :: 2020-03-19 16:47:27.395
End insertion :: 2020-03-19 16:48:11.963
The simple, old-school way would be to use the getTime() method on each Timestamp and subtract the results, giving you the number of milliseconds elapsed between the two:
long millisElapsed = endTimeStamp.getTime() - startTimeStamp.getTime();
Using more modern APIs, though, you would probably convert each timestamp to an Instant, and compute the Duration bracketed by those:
Duration elapsedDuration =
Duration.between(startTimeStamp.toInstant(), endTimeStamp.toInstant());
A Duration has considerably more structure and support than a primitive long, but perhaps it's more than you need.
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.
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);
}
This question already has answers here:
How to subtract X days from a date using Java calendar?
(11 answers)
Closed 6 years ago.
I want to subtract days from date in java. But I dont want to use external libraries. I have referred some of questions from stackoverflow but they are suggesting to use external libraries. So I have applied following logic
noOfDays = 24;
Date compareDate = new Date(currentDate - noOfDays * 24 * 60 * 60 * 1000);
System.out.println("compare date " + compareDate);
It is working fine till 24 days.But after 24 days it is giving unexpected result. Is there any solution to this ?
Use java.util.Calendar.
Something like that:
Calendar c = new Calendar()
c.setTime(currentDate);
c.add(Calendar.DAY_OF_MONTH, noOfDays)
compareDate = c.getTime()
You can use a LocalDate (which is part of the JDK since Java 8):
LocalDate today = LocalDate.now();
LocalDate compareDate = today.minusDays(24);
You computation is about integers, which won't fit higher values than the max integer value.
Declare your variable as a long :
long noOfDays = 24;
Date compareDate = new Date(currentDate - noOfDays * 24 * 60 * 60 * 1000);
System.out.println("compare date " + compareDate);
However, as the comments said, this is not the best approach for substracting days, so have a look at better solutions in other answers.
I'm wanting to have my JLabel display values in the format of HH:mm:ss without making use of any external libraries. (the label will update every second)
So for example, the following input in seconds and the desired output are below:
Seconds: Output:
--------------------------------------------------
long seconds = 0 00:00:00
long seconds = 5 00:00:05
long seconds = 500 00:08:20
long seconds = 5000 01:23:20
Note: the seconds value is of type long
I'm aware that typically one would just do the following conversions to get the desired numbers:
long s = 5000; //total seconds
long hrs = (s / 3600) //hours
long mins = ((s%3600)/60) //minutes
long secs = (s%60) //seconds
However, this leaves decimals on the values. Perhaps there is some sort of formatting that will allow me to toss the un-needed decimals.
Options I have come across were String.format(), SimpleDateFormat(), or concatenating a string myself.
The thing is, I will be updating this JLabel every second and sometimes it can count to the equivalent of 5-6 days if not longer.
So I'm looking for someone who has more experience in the area than I, and knows the most efficient way to tackle this issue.
I would use SimpleDateFormat if I were you.
If SDF is too slow for you, profile all your options and pick the fastest one, then refactor the rest of your code until it's fast enough.
Remember that premature optimization is the root of all evil, and that you should only really do any optimizing after you've profiled your code and missed your target execution time.
SimpleDateFormat() is really quite appropriate for your needs.
Use the TimeUnit class, as shown here in combination with the javax.swing.Timer class set to execute at 1 second intervals.
If you don't mind values wrapping then use SimpleDateFormat as follows. Remember x1000 to convert to milliseconds and to manually override the timezone.
long value = 5 * 24 * 3600 + 5000;
// wrapping solution
SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");
// ensure no daylight saving +1 hour
sdf.setTimeZone(TimeZone.getTimeZone("GMT"));
System.out.println(sdf.format(value * 1000));
Output
01:23:20
If you want the hours to go past 23.59.59 then this is the simplest I could come up with. I used DecimalFormat to force at least 2 digits for the hours.
long value = 5 * 24 * 3600 + 5000;
long hours = value / 3600; // whole hours
long mins = value / 60 - hours * 60;
long secs = value % 60;
System.out.println(String.format("%s:%2d:%2d",
new DecimalFormat("00").format(hours), mins, secs));
Output
121:23:20
I've found this to be extremely fast. Try it out. Seconds go from 0 - 59, minutes go from 0 - 59, hours go from 0 - 2,562,047,788,015. Afterwards the hours become negative and begin going towards that maximum.
performing the "+" operator on Strings is very slow. A StringBuilder performs grouping strings together the fastest from what I've seen. You should also be using "chars" not "String/Byte" Bytes are very slow as well. I'd prefer doing only multiplication however dividing by 36 and 6 give decimals that are to large for holding.
StringBuilder sb = new StringBuilder(8);
long hours = time / 3600000;
long minutes = (time - hours * 3600000) / 60000;
long seconds = (time - hours * 3600000 - minutes * 60000) / 1000;
if (hours < 10)
sb.append('0');
sb.append(hours);
sb.append(':');
if (minutes < 10)
sb.append('0');
sb.append(minutes);
sb.append(':');
if (seconds < 10)
sb.append('0');
sb.append(seconds);
String formattedTime = sb.toString();
.....
If you don't want to use a formatter class, you can get your work done by using basic operations like conversion among wrapper classes and String operations. Take a look at this code:
long h, m, s; // Initialize them after calculation.
String h1, m1, s1;
h1 = Long.toString( h );
m1 = Long.toString( m );
s1 = Long.toString( s );
if ( s1.length() < 2 )
s1 = "0" + s1;
if ( m1.length() < 2 )
m1 = "0" + m1;
if ( h1.length() < 2 )
h1 = "0" + h1;
String output = h1+":"+m1+":"+s1;
Supposing you have correctly calculated values of seconds, minutes and hours, you can gather String versions of these variables, then format them with a simple length check and finally concatenate these time unit parts.
i think you want to do the math you indicated, but take the floor of each value. then concatenate..
public class Test{
public static void main(String args[]){
double d = -100.675;
float f = -90;
System.out.println(Math.floor(d));
System.out.println(Math.floor(f));
System.out.println(Math.ceil(d));
System.out.println(Math.ceil(f));
}
}