How to subtract dates using java.sql.Timestamp [duplicate] - java

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.

Related

Java equivalent syntax for time difference code in C# [duplicate]

This question already has answers here:
Calculating time difference in Milliseconds
(9 answers)
Closed 4 years ago.
How can be write below c# code in java?
var startTime = DateTime.Now;
//some code
Duration = DateTime.Now.Subtract(startTime).TotalMilliseconds;
value in Duration variable is float.
Pretty the same.
Date startTime = new Date();
//some code
long duration = new Date().getTime() - startTime.getTime();

How to calculate the time difference in seconds? [duplicate]

This question already has answers here:
Java 8: Calculate difference between two ZonedDateTime
(3 answers)
Closed 5 years ago.
I have two Datetime strings:
val formatter = DateTimeFormatter.ofPattern("yyyy-MMM-dd-hh-mm-ss")
val startTime = formatter format ZonedDateTime.now(ZoneId.of("UTC"))
//...
val endTime = formatter format ZonedDateTime.now(ZoneId.of("UTC"))
How can I calculate the difference in seconds between endTime and startTime?
Use a java.time.temporal.ChronoUnit:
// difference in seconds
ChronoUnit.SECONDS.between(startTime, endTime)
But startTime and endTime must be ZonedDateTime objects, not Strings.
Just keep in mind that the result is floor-rounded - if the real difference is, let's say, 1999 milliseconds, the code above will return 1 (because 1999 milliseconds are not enough to make 2 seconds).
Another detail is that you can use ZoneOffset.UTC instead of ZoneId.of("UTC"), as the result is the same.
Actually, if you're working with UTC, why not use Instant.now() instead? The between method above works the same way with Instant's:
val start = Instant.now()
val end = Instant.now()
val diffInSecs = ChronoUnit.SECONDS.between(start, end)

Find the difference between two dates (Inclusive of start and end date) in Java [duplicate]

This question already has answers here:
Calculating difference in dates in Java
(7 answers)
Closed 5 years ago.
I need to find the difference between two dates in Java and the difference should be inclusive of start and end date. I tried using below piece of code but it is not including start and end date.
long diffDays = Days.daysBetween(new DateTime(startDate), new DateTime(endDate)).getDays();
Is there any utility method to achieve this?
If you're not using a library this would be one of the method:
public static Map<TimeUnit,Long> computeDiff(Date date1, Date date2) {
long diffInMillies = date2.getTime() - date1.getTime();
List<TimeUnit> units = new ArrayList<TimeUnit>(EnumSet.allOf(TimeUnit.class));
Collections.reverse(units);
Map<TimeUnit,Long> result = new LinkedHashMap<TimeUnit,Long>();
long milliesRest = diffInMillies;
for ( TimeUnit unit : units ) {
long diff = unit.convert(milliesRest,TimeUnit.MILLISECONDS);
long diffInMilliesForUnit = unit.toMillis(diff);
milliesRest = milliesRest - diffInMilliesForUnit;
result.put(unit,diff);
}
return result;
}
Or else you could use Joda

How to format Milliseconds [duplicate]

This question already has answers here:
How do I format a number in Java?
(9 answers)
Closed 6 years ago.
In my code I'm getting milliseconds using
// elaspsed time in milliseconds
public long getElapsedTime() {
if (running) {
return System.currentTimeMillis() - startTime;
}
return stopTime - startTime;
}
As long is a whole number Where as I want to get the milliseconds in 00.0000 format
However I've tried this so far
return ((System.currentTimeMillis() - startTime) / 1000f);
but I am not getting to particular format
It is not possible for you to set the return type to long and return a double or String value.
However if you need to format a millisecond value to the provided format, you should be able to get it done using following code snippet.
String.format("%d.%d", TimeUnit.MILLISECONDS.toSeconds(millies),millies%1000);

The difference between two java.sql.Time objects measured in minutes [duplicate]

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

Categories